target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
src/DateTimePicker.js
MYOB-Technology/react-bootstrap-datetimepicker
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import DateTimePickerDate from './DateTimePickerDate.js'; import DateTimePickerTime from './DateTimePickerTime.js'; import Constants from './Constants.js'; export default class DateTimePicker extends Component { static propTypes = { showDatePicker: PropTypes.bool, showTimePicker: PropTypes.bool, subtractMonth: PropTypes.func.isRequired, addMonth: PropTypes.func.isRequired, viewDate: PropTypes.object.isRequired, selectedDate: PropTypes.object.isRequired, showToday: PropTypes.bool, viewMode: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), mode: PropTypes.oneOf([ Constants.MODE_DATE, Constants.MODE_MONTH, Constants.MODE_DATETIME, Constants.MODE_TIME, ]), daysOfWeekDisabled: PropTypes.array, setSelectedMonth: PropTypes.func.isRequired, setSelectedDate: PropTypes.func.isRequired, subtractYear: PropTypes.func.isRequired, addYear: PropTypes.func.isRequired, setViewMonth: PropTypes.func.isRequired, setViewYear: PropTypes.func.isRequired, subtractHour: PropTypes.func.isRequired, addHour: PropTypes.func.isRequired, subtractMinute: PropTypes.func.isRequired, addMinute: PropTypes.func.isRequired, addDecade: PropTypes.func.isRequired, subtractDecade: PropTypes.func.isRequired, togglePeriod: PropTypes.func.isRequired, minDate: PropTypes.object, maxDate: PropTypes.object, widgetClasses: PropTypes.object, widgetStyle: PropTypes.object, togglePicker: PropTypes.func, setSelectedHour: PropTypes.func, setSelectedMinute: PropTypes.func, setToday: PropTypes.func, calculatePosition: PropTypes.func, }; renderDatePicker = () => { if (this.props.showDatePicker) { return ( <li> <DateTimePickerDate addDecade={this.props.addDecade} addMonth={this.props.addMonth} addYear={this.props.addYear} daysOfWeekDisabled={this.props.daysOfWeekDisabled} maxDate={this.props.maxDate} minDate={this.props.minDate} selectedDate={this.props.selectedDate} setSelectedMonth={this.props.setSelectedMonth} setSelectedDate={this.props.setSelectedDate} setViewMonth={this.props.setViewMonth} setViewYear={this.props.setViewYear} showToday={this.props.showToday} subtractDecade={this.props.subtractDecade} subtractMonth={this.props.subtractMonth} subtractYear={this.props.subtractYear} viewDate={this.props.viewDate} viewMode={this.props.viewMode} mode={this.props.mode} calculatePosition={this.props.calculatePosition} /> </li> ); } }; componentWillUpdate = (nextProps, newState) => { this.shouldCalculatePosition = false; if (nextProps.showTimePicker !== this.props.showTimePicker) { this.shouldCalculatePosition = true; } }; componentDidUpdate = () => { if (this.shouldCalculatePosition) { this.props.calculatePosition(); } }; renderTimePicker = () => { if (this.props.showTimePicker) { return ( <li> <DateTimePickerTime addHour={this.props.addHour} addMinute={this.props.addMinute} mode={this.props.mode} selectedDate={this.props.selectedDate} setSelectedHour={this.props.setSelectedHour} setSelectedMinute={this.props.setSelectedMinute} subtractHour={this.props.subtractHour} subtractMinute={this.props.subtractMinute} togglePeriod={this.props.togglePeriod} viewDate={this.props.viewDate} /> </li> ); } }; renderSwitchButton = () => { return this.props.mode === Constants.MODE_DATETIME ? ( <li> <span className="btn picker-switch" onClick={this.props.togglePicker} style={{ width: '100%' }} > <span className={classNames( 'glyphicon', this.props.showTimePicker ? 'glyphicon-calendar' : 'glyphicon-time', )} /> </span> </li> ) : this.props.mode === Constants.MODE_DATE ? ( <li> <span className="btn btn-today" onClick={this.props.setToday} style={{ width: '100%' }} > Today </span> </li> ) : null; }; render() { const widgetClass = classNames( 'bootstrap-datetimepicker-widget', 'dropdown-menu', this.props.widgetClasses, ); return ( <div className={widgetClass} style={this.props.widgetStyle}> <ul className="list-unstyled"> {this.renderDatePicker()} {this.renderSwitchButton()} {this.renderTimePicker()} </ul> </div> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/env/FileEnvVariables.js
digitalorigin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; export default () => ( <span> <span id="feature-file-env-original-1"> {process.env.REACT_APP_ORIGINAL_1} </span> <span id="feature-file-env-original-2"> {process.env.REACT_APP_ORIGINAL_2} </span> <span id="feature-file-env"> {process.env.REACT_APP_DEVELOPMENT} {process.env.REACT_APP_PRODUCTION} </span> <span id="feature-file-env-x">{process.env.REACT_APP_X}</span> </span> );
node_modules/enzyme/test/ComplexSelector-spec.js
sharonjean/React-Netflix
import { describeWithDOM } from './_helpers'; import React from 'react'; import { expect } from 'chai'; import { mount, shallow, } from '../src/'; const tests = [ { name: 'mount', renderMethod: mount, describeMethod: describeWithDOM, }, { name: 'shallow', renderMethod: shallow, describeMethod: describe, }, ]; describe('ComplexSelector', () => { tests.forEach(({ describeMethod, name, renderMethod }) => { describeMethod(name, () => { it('simple descendent', () => { const wrapper = renderMethod( <div> <div className="top-div"> <span>inside top div</span> </div> <div className="bottom-div"></div> <span /> </div> ); expect(wrapper.find('span').length).to.equal(2); expect(wrapper.find('.top-div span').length).to.equal(1); }); it('nested descendent', () => { const wrapper = renderMethod( <div> <div className="my-div"> <h1 /> <div> <div className="my-div"> <h1 /> </div> </div> </div> <h1 /> </div> ); expect(wrapper.find('h1').length).to.equal(3); expect(wrapper.find('.my-div h1').length).to.equal(2); }); it('deep descendent', () => { const wrapper = renderMethod( <div> <div> <div className="inner"> <span> <div className="way-inner"> <h1 /> </div> </span> </div> </div> <h1 /> </div> ); expect(wrapper.find('h1').length).to.equal(2); expect(wrapper.find('div .inner span .way-inner h1').length).to.equal(1); }); it('direct descendent', () => { const wrapper = renderMethod( <div> <div className="container"> <div className="to-find">Direct</div> <div> <div className="to-find">Nested</div> </div> </div> <div className="to-find">Outside</div> </div> ); expect(wrapper.find('.to-find').length).to.equal(3); const descendent = wrapper.find('.container > .to-find'); expect(descendent.length).to.equal(1); expect(descendent.text()).to.equal('Direct'); }); it('simple adjacent', () => { const wrapper = renderMethod( <div> <div className="to-find" /> <div className="sibling">Adjacent</div> <div className="sibling">Not Adjacent</div> </div> ); expect(wrapper.find('.sibling').length).to.equal(2); const toFind = wrapper.find('.to-find + .sibling'); expect(toFind.length).to.equal(1); expect(toFind.text()).to.equal('Adjacent'); }); it('nested adjacent', () => { const wrapper = renderMethod( <div> <div className="to-find" /> <div className="sibling">Adjacent</div> <div> <div className="sibling">Not Adjacent</div> <div> <div className="to-find" /> <div className="sibling">Adjacent</div> </div> <div className="to-find">Not Adjacent</div> </div> </div> ); expect(wrapper.find('.to-find').length).to.equal(3); const toFind = wrapper.find('.to-find + .sibling'); expect(toFind.length).to.equal(2); toFind.map(found => expect(found.text()).to.equal('Adjacent')); }); it('simple general siblings', () => { const wrapper = renderMethod( <div> <span className="to-find" /> <span /> <span /> <span /> <div> <span /> </div> </div> ); expect(wrapper.find('.to-find ~ span').length).to.equal(3); }); it('nested general siblings', () => { const wrapper = renderMethod( <div> <span>Top</span> <span /> <span /> <div> <div> <span>Top</span> <span /> <span /> </div> </div> </div> ); const spans = wrapper.find('span'); const siblings = wrapper.find('span ~ span'); expect(spans.length - 2).to.equal(siblings.length); siblings.map(sibling => expect(sibling.text()).to.not.equal('Top')); }); it('.foo + div > span', () => { const wrapper = renderMethod( <div> <div className="foo" /> <div> <span /> </div> <div> <span /> </div> </div> ); expect(wrapper.find('.foo + div > span').length).to.equal(1); }); }); }); });
src/components/LocationItem.js
afikris6/afikris6.github.io
import React from 'react'; import PropTypes from 'prop-types'; import { Textfield, ListItem, ListItemContent, ListItemAction } from 'react-mdl'; const LocationItem = ({ subtitle, textField, content, onClick, children }) => ( <ListItem twoLine onClick={onClick}> <ListItemContent subtitle={subtitle}> {textField && <Textfield autoFocus label="Location" value={textField.value} onKeyDown={e => { if (e.key === 'Enter') textField.onSubmit(); } } onChange={e => textField.onChange(e.currentTarget.value) }/>} {content} </ListItemContent> <ListItemAction> <span> {children} </span> </ListItemAction> </ListItem> ); LocationItem.propTypes = { subtitle: PropTypes.string, textField: PropTypes.object, content: PropTypes.string, onClick: PropTypes.func, children: PropTypes.oneOfType([PropTypes.element, PropTypes.array]) }; export default LocationItem;
ajax/libs/clappr/0.0.37/clappr.js
Piicksarn/cdnjs
require=(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; 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'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],2:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function assertObject(x) { if (!isObject(x)) throw $TypeError(x + ' is not an Object'); return x; } function setupGlobals(global) { global.Symbol = Symbol; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { assertObject: assertObject, createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, toProperty: toProperty, type: types, typeof: typeOf, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; var toObject = $traceurRuntime.toObject; function spread() { var rv = [], k = 0; for (var i = 0; i < arguments.length; i++) { var valueToSpread = toObject(arguments[i]); for (var j = 0; j < valueToSpread.length; j++) { rv[k++] = valueToSpread[j]; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; } if (superClass === null) return null; throw new $TypeError(); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw new Error(("\"" + action + "\" on closed generator")); case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime.assertObject($traceurRuntime), canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; return this.value_ = this.func.call(global); }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils"; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x | 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function toInteger(x) { x = +x; if (isNaN(x)) return 0; if (!isFinite(x) || x === 0) return x; return x > 0 ? Math.floor(x) : Math.ceil(x); } var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get toInteger() { return toInteger; }, get toLength() { return toLength; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array"; var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__3.toInteger, toLength = $__3.toLength, toObject = $__3.toObject, isCallable = $__3.isCallable; function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } return { get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__5; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator"; var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toObject = $__6.toObject, toUint32 = $__6.toUint32; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__5, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__5), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map"; var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError("Constructor Map requires 'new'"); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError("Map can not be reentrantly initialised"); } initMap(this); if (iterable !== null && iterable !== undefined) { var iter = iterable[Symbol.iterator]; if (iter !== undefined) { for (var $__8 = iterable[Symbol.iterator](), $__9; !($__9 = $__8.next()).done; ) { var $__10 = $traceurRuntime.assertObject($__9.value), key = $__10[0], value = $__10[1]; { this.set(key, value); } } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; } }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0, len = this.entries_.length; i < len; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } } }, {}); return {get Map() { return Map; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object"; var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__11.toInteger, toLength = $__11.toLength, toObject = $__11.toObject, isCallable = $__11.isCallable; var $__11 = $traceurRuntime.assertObject($traceurRuntime), defineProperty = $__11.defineProperty, getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor, getOwnPropertyNames = $__11.getOwnPropertyNames, keys = $__11.keys, privateNames = $__11.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; } }; }); System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap"; var $__default = function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { scheduleFlush(); } }; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 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() { 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; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise"; var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, cast: function(x) { if (x instanceof this) return x; if (isPromise(x)) { var result = getDeferred(this); chain(x, result.resolve, result.reject); return result.promise; } return this.resolve(x); }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } return {get Promise() { return Promise; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String"; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"; var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map; var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")), codePointAt = $__14.codePointAt, contains = $__14.contains, endsWith = $__14.endsWith, fromCodePoint = $__14.fromCodePoint, repeat = $__14.repeat, raw = $__14.raw, startsWith = $__14.startsWith; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")), fill = $__14.fill, find = $__14.find, findIndex = $__14.findIndex; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")), entries = $__14.entries, keys = $__14.keys, values = $__14.values; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")), assign = $__14.assign, is = $__14.is, mixin = $__14.mixin; function maybeDefineMethod(object, name, value) { if (!(name in object)) { Object.defineProperty(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } function polyfillCollections(global) { if (!global.Map) global.Map = Map; } function polyfillString(String) { maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); } function polyfillArray(Array, Symbol) { maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); if (Symbol && Symbol.iterator) { Object.defineProperty(Array.prototype, Symbol.iterator, { value: values, configurable: true, enumerable: false, writable: true }); } } function polyfillObject(Object) { maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } function polyfill(global) { polyfillPromise(global); polyfillCollections(global); polyfillString(global.String); polyfillArray(global.Array, global.Symbol); polyfillObject(global.Object); } polyfill(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfill(global); }; return {}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import"; var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills")); return {}; }); System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + ''); }).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"FWaASH":1}],3:[function(require,module,exports){ /*! * jQuery JavaScript Library v2.1.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-23T21:10Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return a 'clean' array ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, Expr, getText, isXML, compile, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select t=''><option selected=''></option></select>"; // Support: IE8, Opera 10-12 // Nothing should be selected when empty strings follow ^= or $= or *= if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ); // #11217 - WebKit loses check when the name is after the checked attribute div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || // Support: Android < 4.0 src.defaultPrevented === undefined && src.getPreventDefault && src.getPreventDefault() ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" + "-moz-box-sizing:content-box;box-sizing:content-box", docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" + "margin-top:1px"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" + "position:absolute;top:1%"; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { jQuery.extend(support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); // Clean up the div for other support tests. div.innerHTML = ""; return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Get default display if display is currently "none" if ( display === "none" ) { display = defaultDisplay( elem.nodeName ); } if ( display === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.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( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); },{}],4:[function(require,module,exports){ /** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; },{}],5:[function(require,module,exports){ (function( factory ) { if (typeof define !== 'undefined' && define.amd) { define(['jquery'], factory); } else if (typeof module !== 'undefined' && module.exports) { var $ = require('jquery'); module.exports = factory( $ ); } else { window.scrollMonitor = factory( jQuery ); } })(function( $ ) { var exports = {}; var $window = $(window); var $document = $(document); var watchers = []; var VISIBILITYCHANGE = 'visibilityChange'; var ENTERVIEWPORT = 'enterViewport'; var FULLYENTERVIEWPORT = 'fullyEnterViewport'; var EXITVIEWPORT = 'exitViewport'; var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport'; var LOCATIONCHANGE = 'locationChange'; var STATECHANGE = 'stateChange'; var eventTypes = [ VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE ]; var defaultOffsets = {top: 0, bottom: 0}; exports.viewportTop; exports.viewportBottom; exports.documentHeight; exports.viewportHeight = windowHeight(); var previousDocumentHeight; var latestEvent; function windowHeight() { return window.innerHeight || document.documentElement.clientHeight; } var calculateViewportI; function calculateViewport() { exports.viewportTop = $window.scrollTop(); exports.viewportBottom = exports.viewportTop + exports.viewportHeight; exports.documentHeight = $document.height(); if (exports.documentHeight !== previousDocumentHeight) { calculateViewportI = watchers.length; while( calculateViewportI-- ) { watchers[calculateViewportI].recalculateLocation(); } previousDocumentHeight = exports.documentHeight; } } function recalculateWatchLocationsAndTrigger() { exports.viewportHeight = windowHeight(); calculateViewport(); updateAndTriggerWatchers(); } var recalculateAndTriggerTimer; function debouncedRecalcuateAndTrigger() { clearTimeout(recalculateAndTriggerTimer); recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 ); } var updateAndTriggerWatchersI; function updateAndTriggerWatchers() { // update all watchers then trigger the events so one can rely on another being up to date. updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].update(); } updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].triggerCallbacks(); } } function ElementWatcher( watchItem, offsets ) { var self = this; this.watchItem = watchItem; if (!offsets) { this.offsets = defaultOffsets; } else if (offsets === +offsets) { this.offsets = {top: offsets, bottom: offsets}; } else { this.offsets = $.extend({}, defaultOffsets, offsets); } this.callbacks = {}; // {callback: function, isOne: true } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport; var wasFullyInViewport; var wasAboveViewport; var wasBelowViewport; var listenerToTriggerListI; var listener; function triggerCallbackArray( listeners ) { if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while( listenerToTriggerListI-- ) { listener = listeners[listenerToTriggerListI]; listener.callback.call( self, latestEvent ); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks() { if (this.isInViewport && !wasInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); } if (this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); } switch( true ) { case wasInViewport !== this.isInViewport: case wasFullyInViewport !== this.isFullyInViewport: case wasAboveViewport !== this.isAboveViewport: case wasBelowViewport !== this.isBelowViewport: triggerCallbackArray( this.callbacks[STATECHANGE] ); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function() { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var elementLocation = $(this.watchItem).offset(); this.top = elementLocation.top; this.bottom = elementLocation.top + this.watchItem.offsetHeight; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = exports.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray( this.callbacks[LOCATIONCHANGE] ); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } ElementWatcher.prototype = { on: function( event, callback, isOne ) { // trigger the event if it applies to the element right now. switch( true ) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport: callback(); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({callback: callback, isOne: isOne}); } else { throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, off: function( event, callback ) { if (this.callbacks[event]) { for (var i = 0, item; item = this.callbacks[event][i]; i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, one: function( event, callback ) { this.on( event, callback, true); }, recalculateSize: function() { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; }, update: function() { this.isAboveViewport = this.top < exports.viewportTop; this.isBelowViewport = this.bottom > exports.viewportBottom; this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop); this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); }, destroy: function() { var index = watchers.indexOf(this), self = this; watchers.splice(index, 1); for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]].length = 0; } }, // prevent recalculating the element location lock: function() { this.locked = true; }, unlock: function() { this.locked = false; } }; var eventHandlerFactory = function (type) { return function( callback, isOne ) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; ElementWatcher.prototype[type] = eventHandlerFactory(type); } try { calculateViewport(); } catch (e) { $(calculateViewport); } function scrollMonitorListener(event) { latestEvent = event; calculateViewport(); updateAndTriggerWatchers(); } $window.on('scroll', scrollMonitorListener); $window.on('resize', debouncedRecalcuateAndTrigger); exports.beget = exports.create = function( element, offsets ) { if (typeof element === 'string') { element = $(element)[0]; } if (element instanceof $) { element = element[0]; } var watcher = new ElementWatcher( element, offsets ); watchers.push(watcher); watcher.update(); return watcher; }; exports.update = function() { latestEvent = null; calculateViewport(); updateAndTriggerWatchers(); }; exports.recalculateLocations = function() { exports.documentHeight = 0; exports.update(); }; return exports; }); },{"jquery":3}],6:[function(require,module,exports){ // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); },{}],"base_object":[function(require,module,exports){ module.exports=require('2HNVgz'); },{}],"2HNVgz":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('./events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./events":13,"./utils":24,"underscore":6}],"container_plugin":[function(require,module,exports){ module.exports=require('6xH8xW'); },{}],"6xH8xW":[function(require,module,exports){ "use strict"; var BaseObject = require('./base_object'); var ContainerPlugin = function ContainerPlugin(options) { $traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]); this.bindEvents(); }; var $ContainerPlugin = ContainerPlugin; ($traceurRuntime.createClass)(ContainerPlugin, { enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); }, bindEvents: function() {}, destroy: function() { this.stopListening(); } }, {}, BaseObject); module.exports = ContainerPlugin; },{"./base_object":"2HNVgz"}],"core_plugin":[function(require,module,exports){ module.exports=require('it+usN'); },{}],"it+usN":[function(require,module,exports){ "use strict"; var BaseObject = require('./base_object'); var CorePlugin = function CorePlugin(core) { $traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]); this.core = core; }; var $CorePlugin = CorePlugin; ($traceurRuntime.createClass)(CorePlugin, { getExternalInterface: function() { return {}; }, destroy: function() {} }, {}, BaseObject); module.exports = CorePlugin; },{"./base_object":"2HNVgz"}],13:[function(require,module,exports){ (function (global){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log'); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; if (global.DEBUG) { if (Log.BLACKLIST.indexOf(name) < 0) Log.info(klass, 'event ' + name + ' triggered'); } if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); module.exports = Events; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../plugins/log":61,"underscore":6}],14:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var render=function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'), 'seek_time': _.template('<span data-seek-time></span>'), 'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'), 'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'), 'background_button': _.template('<div class="background-button-wrapper" data-background-button><span class="background-button-icon" data-background-button></span></div>'), 'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'), 'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}', 'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;color:#000;background-color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}', 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:all,.6s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.6s,ease-out;-o-transition:all,.6s,ease-out;transition:all,.6s,ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 15px;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:5px;width:100%;height:32px;vertical-align:middle;-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:10px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:none;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5)}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:block}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all,.2s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.2s,ease-out;-o-transition:all,.2s,ease-out;transition:all,.2s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}', 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}', 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}', 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.background-button[data-background-button].pointer-enabled{cursor:pointer}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{font-family:Player;cursor:pointer;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}', 'dvr_controls': '.dvr-controls[data-dvr-controls]{display:inline-block;color:#fff;line-height:32px;font-size:12px;font-weight:700;margin-left:5px}.dvr-controls[data-dvr-controls] .live-info{cursor:default}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:10px;height:10px;border-radius:5px;margin-right:3px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;font-size:12px;height:32px;padding:0;opacity:.7}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:10px;height:10px;border-radius:5px;margin-right:3px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}', 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":6}],"VbgHr3":[function(require,module,exports){ "use strict"; var UIObject = require('../base/ui_object'); var Playback = function Playback(options) { $traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]); this.settings = {}; }; var $Playback = Playback; ($traceurRuntime.createClass)(Playback, { play: function() {}, pause: function() {}, stop: function() {}, seek: function(time) {}, getDuration: function() { return 0; }, isPlaying: function() { return false; }, getPlaybackType: function() { return 'no_op'; }, isHighDefinitionInUse: function() { return false; }, volume: function(value) {}, destroy: function() { this.$el.remove(); } }, {}, UIObject); Playback.canPlay = (function(source) { return false; }); module.exports = Playback; },{"../base/ui_object":"8lqCAT"}],"playback":[function(require,module,exports){ module.exports=require('VbgHr3'); },{}],17:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style></style>').html(_.template(JST.CSS[name])(options)); }}; module.exports = Styler; },{"./jst":14,"jquery":3,"underscore":6}],"ui_container_plugin":[function(require,module,exports){ module.exports=require('XSLDWT'); },{}],"XSLDWT":[function(require,module,exports){ "use strict"; var UIObject = require('./ui_object'); var UIContainerPlugin = function UIContainerPlugin(options) { $traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]); this.enabled = true; this.bindEvents(); }; var $UIContainerPlugin = UIContainerPlugin; ($traceurRuntime.createClass)(UIContainerPlugin, { enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, bindEvents: function() {}, destroy: function() { this.remove(); } }, {}, UIObject); module.exports = UIContainerPlugin; },{"./ui_object":"8lqCAT"}],"ui_core_plugin":[function(require,module,exports){ module.exports=require('gNZMEo'); },{}],"gNZMEo":[function(require,module,exports){ "use strict"; var UIObject = require('./ui_object'); var UICorePlugin = function UICorePlugin(core) { $traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]); this.core = core; this.enabled = true; this.bindEvents(); this.render(); }; var $UICorePlugin = UICorePlugin; ($traceurRuntime.createClass)(UICorePlugin, { bindEvents: function() {}, getExternalInterface: function() { return {}; }, enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, destroy: function() { this.remove(); }, render: function() { this.$el.html(this.template()); this.$el.append(this.styler.getStyleFor(this.name)); this.core.$el.append(this.el); return this; } }, {}, UIObject); module.exports = UICorePlugin; },{"./ui_object":"8lqCAT"}],"8lqCAT":[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('./base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var UIObject = function UIObject(options) { $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.cid = _.uniqueId('c'); this._ensureElement(); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./base_object":"2HNVgz","./utils":24,"jquery":3,"underscore":6}],"ui_object":[function(require,module,exports){ module.exports=require('8lqCAT'); },{}],24:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var formatTime = function(time) { time = time * 1000; time = parseInt(time / 1000); var seconds = time % 60; time = parseInt(time / 60); var minutes = time % 60; time = parseInt(time / 60); var hours = time % 24; var out = ""; if (hours && hours > 0) out += ("0" + hours).slice(-2) + ":"; out += ("0" + minutes).slice(-2) + ":"; out += ("0" + seconds).slice(-2); return out.trim(); }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; module.exports = { extend: extend, formatTime: formatTime, Fullscreen: Fullscreen }; },{"underscore":6}],"195Wj5":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i)); Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent)); module.exports = Browser; },{}],"browser":[function(require,module,exports){ module.exports=require('195Wj5'); },{}],27:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Container = function Container(options) { $traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]); this.playback = options.playback; this.settings = this.playback.settings; this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; this.bindEvents(); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return {'data-container': ''}; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.playback, 'playback:progress', this.progress); this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated); this.listenTo(this.playback, 'playback:ready', this.ready); this.listenTo(this.playback, 'playback:buffering', this.buffering); this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull); this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate); this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata); this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged); this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged); this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl); this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl); this.listenTo(this.playback, 'playback:ended', this.ended); this.listenTo(this.playback, 'playback:play', this.playing); this.listenTo(this.playback, 'playback:error', this.error); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger('container:playbackstate'); }, playbackDvrStateChanged: function(dvrInUse) { this.settings = this.playback.settings; this.trigger('container:dvr', dvrInUse); }, statsAdd: function(metric) { this.trigger('container:stats:add', metric); }, statsReport: function(metrics) { this.trigger('container:stats:report', metrics); }, getPlaybackType: function() { return this.playback.getPlaybackType(); }, destroy: function() { this.trigger('container:destroyed', this, this.name); this.playback.destroy(); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger('container:ready', this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, getDuration: function() { return this.playback.getDuration(); }, error: function(error) { this.$el.prepend(error.render().el); this.trigger('container:error', { error: error, container: this }, this.name); }, loadedMetadata: function(duration) { this.trigger('container:loadedmetadata', duration); }, timeUpdated: function(position, duration) { this.trigger('container:timeupdate', position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger('container:play', this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger('container:stop', this.name); this.playback.stop(); }, pause: function() { this.trigger('container:pause', this.name); this.playback.pause(); }, ended: function() { this.trigger('container:ended', this, this.name); }, clicked: function() { this.trigger('container:click', this, this.name); }, setCurrentTime: function(time) { this.trigger('container:seek', time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.playback.volume(value); }, requestFullscreen: function() { this.trigger('container:fullscreen', this.name); }, buffering: function() { this.trigger('container:state:buffering', this.name); }, bufferfull: function() { this.trigger('container:state:bufferfull', this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger('container:settingsupdate'); }, highDefinitionUpdate: function() { this.trigger('container:highdefinitionupdate'); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger('container:mediacontrol:disable'); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger('container:mediacontrol:enable'); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); module.exports = Container; },{"../../base/styler":17,"../../base/ui_object":"8lqCAT","underscore":6}],28:[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":27}],29:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Container = require('../container'); var $ = require('jquery'); var ContainerFactory = function ContainerFactory(options, loader) { $traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]); this.options = options; this.loader = loader; }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { createContainers: function() { return $.Deferred(function(promise) { promise.resolve(_.map(this.options.sources, function(source) { return this.createContainer(source); }, this)); }.bind(this)); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay(source.toString()); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var options = _.extend({}, this.options, { src: source, autoPlay: !!this.options.autoPlay }); var playback = new playbackPlugin(options); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, 'container:ready', (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(Plugin) { var options = _.extend(this.options, { container: container, src: source }); container.addPlugin(new Plugin(options)); }, this); } }, {}, BaseObject); module.exports = ContainerFactory; },{"../../base/base_object":"2HNVgz","../container":28,"jquery":3,"underscore":6}],30:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":29}],31:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var UIObject = require('../../base/ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Styler = require('../../base/styler'); var MediaControl = require('../media_control'); var PlayerInfo = require('../player_info'); var Mediator = require('../mediator'); var Core = function Core(options) { var $__0 = this; $traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]); PlayerInfo.options = options; this.options = options; this.plugins = []; this.containers = []; this.createContainers(options); document.addEventListener('fullscreenchange', (function() { return $__0.exit(); })); document.addEventListener('MSFullscreenChange', (function() { return $__0.exit(); })); document.addEventListener('mozfullscreenchange', (function() { return $__0.exit(); })); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, createContainers: function(options) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.containerFactory = new ContainerFactory(options, options.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.setFullscreen(); } else { this.setPlayerSize(); } Mediator.trigger('player:resize'); }, setFullscreen: function() { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); PlayerInfo.currentSize = { width: $(window).width(), height: $(window).height() }; }, resize: function(height, width) { var size = { height: height, width: width }; this.$el.css(size); PlayerInfo.currentSize = size; Mediator.trigger('player:resize', size); }, setPlayerSize: function() { this.resize(this.options.height, this.options.width); this.$el.removeClass('fullscreen'); }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isString(sources) ? [sources] : sources; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.options = _(this.options).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.options.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options)); this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false)); } }, createMediaControl: function(options) { if (options.mediacontrol && options.mediacontrol.external) { return new options.mediacontrol.external(options); } else { return new MediaControl(options); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.options.width = this.options.width || this.$el.width(); this.options.height = this.options.height || this.$el.height(); this.updateSize(); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"../container_factory":30,"../media_control":"A8Uh+k","../mediator":"veeMMc","../player_info":"Rmed05","jquery":3,"underscore":6}],32:[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":31}],33:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Core = require('../core'); var CoreFactory = function CoreFactory(player, loader) { this.player = player; this.options = player.options; this.loader = loader; this.options.loader = this.loader; }; ($traceurRuntime.createClass)(CoreFactory, { create: function() { this.core = new Core(this.options); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.corePlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }, {}, BaseObject); module.exports = CoreFactory; },{"../../base/base_object":"2HNVgz","../core":32,"underscore":6}],34:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":33}],35:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":36}],36:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var _ = require('underscore'); var PlayerInfo = require('../player_info'); var HTML5VideoPlayback = require('../../playbacks/html5_video'); var FlashVideoPlayback = require('../../playbacks/flash'); var HTML5AudioPlayback = require('../../playbacks/html5_audio'); var HLSVideoPlayback = require('../../playbacks/hls'); var NoOp = require('../../playbacks/no_op'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('../../plugins/poster'); var BackgroundButton = require('../../plugins/background_button'); var DVRControls = require('../../plugins/dvr_controls'); var Loader = function Loader(externalPlugins) { $traceurRuntime.superCall(this, $Loader.prototype, "constructor", []); this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin]; this.corePlugins = [BackgroundButton, DVRControls]; if (externalPlugins) { this.addExternalPlugins(externalPlugins); } }; var $Loader = Loader; ($traceurRuntime.createClass)(Loader, { addExternalPlugins: function(plugins) { var pluginName = function(plugin) { return plugin.prototype.name; }; if (plugins.playback) { this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName); } if (plugins.container) { this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName); } if (plugins.core) { this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName); } PlayerInfo.playbackPlugins = this.playbackPlugins; }, getPlugin: function(name) { var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins); return _.find(allPlugins, function(plugin) { return plugin.prototype.name === name; }); } }, {}, BaseObject); module.exports = Loader; },{"../../base/base_object":"2HNVgz","../../playbacks/flash":48,"../../playbacks/hls":50,"../../playbacks/html5_audio":52,"../../playbacks/html5_video":54,"../../playbacks/no_op":55,"../../plugins/background_button":58,"../../plugins/dvr_controls":60,"../../plugins/poster":63,"../../plugins/spinner_three_bounce":65,"../../plugins/stats":67,"../../plugins/watermark":69,"../player_info":"Rmed05","underscore":6}],"A8Uh+k":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":39}],"media_control":[function(require,module,exports){ module.exports=require('A8Uh+k'); },{}],39:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('../../base/ui_object'); var Utils = require('../../base/utils'); var Mousetrap = require('mousetrap'); var SeekTime = require('../seek_time'); var Mediator = require('../../components/mediator'); var transitionEvents = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'; var MediaControl = function MediaControl(options) { var $__0 = this; $traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]); this.seekTime = new SeekTime(this); this.options = options; this.currentVolume = this.options.mute ? 0 : 100; this.container = options.container; this.container.setVolume(this.currentVolume); this.keepVisible = false; this.addEventListeners(); this.settings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.disabled = false; if (this.container.mediaControlDisabled || this.options.chromeless) { this.disable(); } $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); Mediator.on('player:resize', (function() { return $__0.playerResize(); })); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click [data-seekbar]': 'seek', 'click .bar-background[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseover .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mouseenter .bar-container[data-volume]': 'mousemoveOnSeekBar', 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar', 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, addEventListeners: function() { this.listenTo(this.container, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, 'container:ended', this.ended); }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.options.chromeless) return; this.disabled = false; this.show(); }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); this.trigger('mediacontrol:playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger('mediacontrol:notplaying'); } }, mousemoveOnSeekBar: function(event) { if (this.container.settings.seekEnabled) { var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2); this.$seekBarHover.css({left: offsetX}); this.$seekBarHover.show(); } this.trigger('mediacontrol:mousemove:seekbar', event); }, mouseleaveOnSeekBar: function(event) { this.$seekBarHover.hide(); this.trigger('mediacontrol:mouseleave:seekbar', event); }, playerResize: function() { if (Utils.Fullscreen.isFullscreen()) { this.$fullscreenToggle.addClass('shrink'); } else { this.$fullscreenToggle.removeClass('shrink'); } }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { if (!this.container.settings.seekEnabled) return; this.draggingSeekBar = true; this.$seekBarLoaded.addClass('media-control-notransition'); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.$seekBarLoaded.removeClass('media-control-notransition'); this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageY - this.$volumeBarContainer.offset().top; this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100; this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); }, toggleMute: function() { if (!!this.mute) { this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); this.mute = false; } else { this.container.setVolume(0); this.setVolumeLevel(0); this.mute = true; } }, toggleFullscreen: function() { this.trigger('mediacontrol:fullscreen', this.name); this.resetKeepVisible(); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) { this.disable(); } this.trigger("mediacontrol:containerchanged"); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.show(); this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; if (!this.$volumeBarContainer) return; if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { $__0.$volumeBarContainer.one(transitionEvents, (function() { $__0.$volumeBarContainer.off(transitionEvents); $__0.$volumeBarContainer.hide(); })); $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), 750); }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; if (position < 0) position = duration; this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { if (!this.container.settings.seekEnabled) return; var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); this.setSeekPercentage(pos); }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, isVisible: function() { return !this.$el.hasClass('media-control-hide'); }, show: function(event) { var $__0 = this; if (this.disabled || this.isVisible()) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { if (this.hideId) { clearTimeout(this.hideId); } this.$el.show(); this.trigger('mediacontrol:show', this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; if (this.hideId) { clearTimeout(this.hideId); } if (!this.isVisible()) return; if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { if (this.$volumeBarContainer) { this.$volumeBarContainer.hide(); } this.trigger('mediacontrol:hide', this.name); this.$el.addClass('media-control-hide'); } }, settingsUpdate: function() { this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.render(); }, highDefinitionUpdate: function() { if (this.container.isHighDefinitionInUse()) { this.$el.find('button[data-hd-indicator]').addClass("enabled"); } else { this.$el.find('button[data-hd-indicator]').removeClass("enabled"); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]'); this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]'); this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var $__0 = this; if (!this.container.isReady) { this.listenToOnce(this.container, "container:ready", (function() { return $__0.setVolumeLevel(value); })); } else { var containerHeight = this.$volumeBarContainer.height(); var barHeight = this.$volumeBarBackground.height(); var offset = (containerHeight - barHeight) / 2.0; var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset; this.$volumeBarFill.css({height: value + '%'}); this.$volumeBarScrubber.css({bottom: pos}); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } } }, setSeekPercentage: function(value) { if (value > 100) return; var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0); this.currentSeekPercentage = value; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; Mousetrap.bind(['space'], (function() { return $__0.togglePlayPause(); })); }, parseColors: function() { var $__0 = this; var translate = { query: { 'seekbar': '.bar-fill-2[data-seekbar]', 'buttons': '[data-media-control] > .media-control-icon, [data-volume]' }, rule: { 'seekbar': 'background-color', 'buttons': 'color' } }; if (this.options.mediacontrol) { var customColors = _.pick(this.options.mediacontrol, 'seekbar', 'buttons'); } _.each(customColors, (function(value, key) { $__0.$el.find(translate.query[key]).css(translate.rule[key], customColors[key]); })); }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); this.$el.html(this.template({settings: this.settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.$volumeBarContainer.hide(); this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) { this.hide(); } this.$seekBarHover.hide(); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (!this.currentSeekPercentage) { this.currentSeekPercentage = 0; } this.setSeekPercentage(this.currentSeekPercentage); this.$el.ready((function() { if (!$__0.container.settings.seekEnabled) { $__0.$seekBarContainer.addClass('seek-disabled'); } $__0.setVolumeLevel($__0.currentVolume); $__0.bindKeyEvents(); })); this.parseColors(); this.seekTime.render(); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"../../components/mediator":"veeMMc","../seek_time":44,"jquery":3,"mousetrap":4,"underscore":6}],"mediator":[function(require,module,exports){ module.exports=require('veeMMc'); },{}],"veeMMc":[function(require,module,exports){ "use strict"; var Events = require('../base/events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"../base/events":13}],"player_info":[function(require,module,exports){ module.exports=require('Rmed05'); },{}],"Rmed05":[function(require,module,exports){ "use strict"; var PlayerInfo = { options: {}, playbackPlugins: [], currentSize: { width: 0, height: 0 } }; module.exports = PlayerInfo; },{}],44:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":45}],45:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var formatTime = require('../../base/utils').formatTime; var SeekTime = function SeekTime(mediaControl) { $traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []); this.mediaControl = mediaControl; this.addEventListeners(); }; var $SeekTime = SeekTime; ($traceurRuntime.createClass)(SeekTime, { get name() { return 'seek_time'; }, get template() { return JST.seek_time; }, get attributes() { return { 'class': 'seek-time hidden', 'data-seek-time': '' }; }, addEventListeners: function() { this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime); this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime); }, showTime: function(event) { var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left; var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0)); var pointerPosition = offset - (this.$el.width() / 2); var currentTime = timePosition * this.mediaControl.container.getDuration() / 100; var options = { timestamp: currentTime, formattedTime: formatTime(currentTime), pointerPosition: pointerPosition }; this.update(options); }, hideTime: function() { this.$el.addClass('hidden'); }, update: function(options) { if (this.mediaControl.container.getPlaybackType() === 'vod') { this.$el.find('[data-seek-time]').text(options.formattedTime); this.$el.css('left', options.pointerPosition); this.$el.removeClass('hidden'); } }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.mediaControl.$el.append(this.el); } }, {}, UIObject); module.exports = SeekTime; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24}],46:[function(require,module,exports){ (function (global){ "use strict"; var BaseObject = require('./base/base_object'); var CoreFactory = require('./components/core_factory'); var Loader = require('./components/loader'); var Mediator = require('./components/mediator'); var _ = require('underscore'); var ScrollMonitor = require('scrollmonitor'); var PlayerInfo = require('./components/player_info'); var Player = function Player(options) { $traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]); window.p = this; this.options = options; this.options.sources = this.normalizeSources(options); this.loader = new Loader(this.options.plugins || []); this.coreFactory = new CoreFactory(this, this.loader); options.height || (options.height = 360); options.width || (options.width = 640); PlayerInfo.currentSize = { width: options.width, height: options.height }; }; var $Player = Player; ($traceurRuntime.createClass)(Player, { attachTo: function(element) { this.options.parentElement = element; this.core = this.coreFactory.create(); if (this.options.autoPlayVisible) { this.bindAutoPlayVisible(this.options.autoPlayVisible); } }, bindAutoPlayVisible: function(option) { var $__0 = this; this.elementWatcher = ScrollMonitor.create(this.core.$el); if (option === 'full') { this.elementWatcher.fullyEnterViewport((function() { return $__0.enterViewport(); })); } else if (option === 'partial') { this.elementWatcher.enterViewport((function() { return $__0.enterViewport(); })); } }, enterViewport: function() { if (this.elementWatcher.top !== 0 && !this.isPlaying()) { this.play(); } }, normalizeSources: function(options) { return _.compact(_.flatten([options.source, options.sources])); }, resize: function(height, width) { this.core.resize(height, width); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); }, play: function() { this.core.mediaControl.container.play(); }, pause: function() { this.core.mediaControl.container.pause(); }, stop: function() { this.core.mediaControl.container.stop(); }, seek: function(time) { this.core.mediaControl.container.setCurrentTime(time); }, setVolume: function(volume) { this.core.mediaControl.container.setVolume(volume); }, mute: function() { this.core.mediaControl.container.setVolume(0); }, unmute: function() { this.core.mediaControl.container.setVolume(100); }, isPlaying: function() { return this.core.mediaControl.container.isPlaying(); } }, {}, BaseObject); global.DEBUG = false; window.Clappr = { Player: Player, Mediator: Mediator }; module.exports = window.Clappr; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./base/base_object":"2HNVgz","./components/core_factory":34,"./components/loader":35,"./components/mediator":"veeMMc","./components/player_info":"Rmed05","scrollmonitor":5,"underscore":6}],47:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var _ = require('underscore'); var $ = require('jquery'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var Flash = function Flash(options) { $traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]); this.src = options.src; this.isRTMP = (this.src.indexOf("rtmp") > -1); this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf"; this.autoPlay = options.autoPlay; this.settings = {default: ['seekbar']}; if (this.isRTMP) { this.settings.left = ["playstop", "volume"]; this.settings.right = ["fullscreen"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } this.isReady = false; this.addListeners(); }; var $Flash = Flash; ($traceurRuntime.createClass)(Flash, { get name() { return 'flash'; }, get tagName() { return 'object'; }, get template() { return JST.flash; }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; if (this.currentState === 'PLAYING') { this.firstPlay(); } else { this.currentState = "IDLE"; this.autoPlay && this.play(); } $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); this.trigger('playback:ready', this.name); }, getPlaybackType: function() { return this.isRTMP ? 'live' : 'vod'; }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash', ''); this.setElement($el[0]); }, isHighDefinitionInUse: function() { return false; }, updateTime: function() { this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name); }, addListeners: function() { Mediator.on(this.uniqueId + ':progress', this.progress, this); Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this); Mediator.on(this.uniqueId + ':statechanged', this.checkState, this); Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this); }, stopListening: function() { $traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); Mediator.off(this.uniqueId + ':flashready'); }, checkState: function() { if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") { this.trigger('playback:buffering', this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger('playback:bufferfull', this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name); } }, firstPlay: function() { this.currentState = "PLAYING"; if (_.isFunction(this.el.playerPlay)) { this.el.playerPlay(this.src); } }, play: function() { if (this.el.getState() === 'PAUSED') { this.currentState = "PLAYING"; this.el.playerResume(); } else if (this.el.getState() !== 'PLAYING') { this.firstPlay(); } this.trigger('playback:play', this.name); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.playerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { return !!(this.isReady && this.currentState === "PLAYING"); }, getDuration: function() { return this.el.getDuration(); }, seek: function(time) { var seekTo = this.el.getDuration() * (time / 100); this.el.playerSeek(seekTo); this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name); if (this.currentState === "PAUSED") { this.pause(); } }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } this.$el.append(style); return this; } }, {}, UIObject); Flash.canPlay = function(resource) { if (resource.indexOf('rtmp') > -1) { return true; } else if (Browser.isFirefox || Browser.isLegacyIE) { return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/); } }; module.exports = Flash; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../components/browser":"195Wj5","../../components/mediator":"veeMMc","jquery":3,"underscore":6}],48:[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":47}],49:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('../../components/mediator'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var HLS = function HLS(options) { $traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]); this.src = options.src; this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf"; this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop"], default: ['seekbar'], right: ["fullscreen", "volume", "hd-indicator"], seekEnabled: true }; this.settings = _.extend({}, this.defaultSettings); this.addListeners(); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'class': 'hls-playback', 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':playbackstate', (function(state) { return $__0.setPlaybackState(state); })); Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) { return $__0.updateHighDefinition(isHD); })); Mediator.on(this.uniqueId + ':playbackerror', (function() { return $__0.flashPlaybackError(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); Mediator.off(this.uniqueId + ':playbackerror'); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.el.globoPlayerSetflushLiveURLCache(true); this.el.globoPlayerSetmaxBufferLength(0); this.autoPlay && this.play(); }, updateHighDefinition: function(isHD) { this.highDefinition = (isHD === "true"); this.trigger('playback:highdefinitionupdate'); }, updateTime: function() { var duration = this.getDuration(); var position = this.el.globoGetPosition(); var livePlayback = this.playbackType === 'live'; if (livePlayback && (position >= duration || position < 0)) { position = duration; } var previousDVRStatus = this.dvrEnabled; this.dvrEnabled = (livePlayback && duration > 240); if (this.dvrEnabled !== previousDVRStatus) { this.updateSettings(); this.trigger('playback:settingsupdate', this.name); } if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) { position = duration; } this.trigger('playback:timeupdate', position, duration, this.name); }, play: function() { if (this.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else if (this.currentState !== "PLAYING") { this.firstPlay(); } this.trigger('playback:play', this.name); }, getPlaybackType: function() { return this.playbackType ? this.playbackType : null; }, getCurrentBitrate: function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinitionInUse: function() { return this.highDefinition; }, getLevels: function() { if (!this.levels || this.levels.length === 0) { this.levels = this.el.globoGetLevels(); } return this.levels; }, setPlaybackState: function(state) { var bufferLength = this.el.globoGetbufferLength(); if (state === "PLAYING_BUFFERING" && bufferLength < 1) { this.trigger('playback:buffering', this.name); this.updateCurrentState(state); } else if (state === "PLAYING") { if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) { this.trigger('playback:bufferfull', this.name); this.updateCurrentState(state); } } else if (state === "PAUSED") { this.updateCurrentState(state); } else if (state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name); this.updateCurrentState(state); } this.lastBufferLength = bufferLength; }, updateCurrentState: function(state) { this.currentState = state; this.updatePlaybackType(); }, updatePlaybackType: function() { this.playbackType = this.el.globoGetType(); if (this.playbackType) { this.playbackType = this.playbackType.toLowerCase(); if (this.playbackType === 'vod') { this.startReportingProgress(); } else { this.stopReportingProgress(); } } this.trigger('playback:playbackstate'); }, startReportingProgress: function() { var $__0 = this; if (!this.reportingProgress) { this.reportingProgress = true; Mediator.on(this.uniqueId + ':fragmentloaded', (function() { return $__0.onFragmentLoaded(); })); } }, stopReportingProgress: function() { Mediator.off(this.uniqueId + ':fragmentloaded'); }, onFragmentLoaded: function() { var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength(); this.trigger('playback:progress', this.el.globoGetPosition(), buffered, this.getDuration(), this.name); }, firstPlay: function() { this.el.globoPlayerLoad(this.src); this.el.globoPlayerPlay(); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.globoPlayerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { if (this.playbackType !== 'live' || this.dvrEnabled) { this.el.globoPlayerPause(); if (this.playbackType === 'live' && this.dvrEnabled) { this.updateDvr(true); } } }, stop: function() { this.el.globoPlayerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { if (this.currentState) { return !!(this.currentState.match(/playing/i)); } return false; }, getDuration: function() { var duration = this.el.globoGetDuration(); if (this.playbackType === 'live') { duration = duration - 10; } return duration; }, seek: function(time) { var duration = this.getDuration(); if (time > 0) { time = duration * time / 100; } if (this.playbackType === 'live') { var dvrInUse = (time >= 0 && duration - time > 5); if (!dvrInUse) { time = -1; } this.updateDvr(dvrInUse); } this.el.globoPlayerSeek(time); this.trigger('playback:timeupdate', time, duration, this.name); }, updateDvr: function(dvrInUse) { var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = dvrInUse; if (this.dvrInUse !== previousDvrInUse) { this.updateSettings(); this.trigger('playback:dvr', this.dvrInUse); this.trigger('playback:stats:add', {'dvr': this.dvrInUse}); } }, flashPlaybackError: function() { this.trigger('playback:stop'); }, timeUpdate: function(time, duration) { this.trigger('playback:timeupdate', time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrInUse) { this.settings.left = ["playpause", "position", "duration"]; } else if (this.dvrEnabled) { this.settings.left = ["playpause"]; } else { this.settings.seekEnabled = false; } }, setElement: function(element) { this.$el = element; this.el = element[0]; }, render: function() { var style = Styler.getStyleFor(this.name); if (Browser.isLegacyIE) { this.setupIE(); } else { this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isIE) { this.$('embed').remove(); } } this.el.id = this.cid; this.$el.append(style); return this; } }, {}, Playback); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8/); }; module.exports = HLS; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","../../components/mediator":"veeMMc","underscore":6}],50:[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":49}],51:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var HTML5Audio = function HTML5Audio(params) { $traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]); this.el.src = params.src; this.settings = { left: ['playpause', 'position', 'duration'], right: ['fullscreen', 'volume'], default: ['seekbar'] }; this.render(); params.autoPlay && this.play(); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended' }; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, getPlaybackType: function() { return "aod"; }, play: function() { this.el.play(); this.trigger('playback:play'); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger('container:timeupdate', 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, timeUpdated: function() { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); }, render: function() { return this; } }, {}, Playback); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"../../base/playback":"VbgHr3"}],52:[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":51}],53:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Browser = require('../../components/browser'); var _ = require('underscore'); var HTML5Video = function HTML5Video(options) { $traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]); this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.isHLS = (this.src.indexOf('m3u8') > -1); this.settings = {default: ['seekbar']}; if (this.isHLS) { this.settings.left = ["playstop"]; this.settings.right = ["fullscreen", "volume"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get tagName() { return 'video'; }, get template() { return JST.html5_video; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'playing': 'playing', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, loadedMetadata: function(e) { this.trigger('playback:loadedmetadata', e.target.duration); this.trigger('playback:settingsupdate'); }, getPlaybackType: function() { return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'; }, isHighDefinitionInUse: function() { return false; }, play: function() { this.el.play(); this.trigger('playback:play'); if (this.isHLS) { this.trigger('playback:timeupdate', 1, 1, this.name); } }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod') { this.trigger('playback:buffering', this.name); } }, waiting: function() { this.trigger('playback:buffering', this.name); }, bufferFull: function() { this.trigger('playback:bufferfull', this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { if (this.getPlaybackType() !== 'live') { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); } }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, typeFor: function(src) { return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) })); this.$el.append(style); this.trigger('playback:ready', this.name); this.options.autoPlay && this.play(); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App); }; module.exports = HTML5Video; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","underscore":6}],54:[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":53}],55:[function(require,module,exports){ "use strict"; module.exports = require('./no_op'); },{"./no_op":56}],56:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var NoOp = function NoOp(options) { $traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]); }; var $NoOp = NoOp; ($traceurRuntime.createClass)(NoOp, { get name() { return 'no_op'; }, get template() { return JST.no_op; }, get attributes() { return {'data-no-op': ''}; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); return this; } }, {}, Playback); NoOp.canPlay = (function(source) { return true; }); module.exports = NoOp; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17}],57:[function(require,module,exports){ (function (process){ "use strict"; var UICorePlugin = require('../../base/ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Mediator = require('../../components/mediator'); var PlayerInfo = require('../../components/player_info'); var BackgroundButton = function BackgroundButton(core) { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $BackgroundButton = BackgroundButton; ($traceurRuntime.createClass)(BackgroundButton, { get template() { return JST.background_button; }, get name() { return 'background_button'; }, get attributes() { return { 'class': 'background-button', 'data-background-button': '' }; }, bindEvents: function() { this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide); this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.updateSize); this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing); this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []); Mediator.off('player:resize', this.updateSize, this); }, settingsUpdate: function() { this.stopListening(); if (this.shouldRender()) { this.render(); this.bindEvents(); if (this.core.mediaControl.container.isPlaying()) { this.playing(); } else { this.notplaying(); } } else { this.hide(); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); } }, shouldRender: function() { var useBackgroundButton = this.core.options.useBackgroundButton === undefined || !!this.core.options.useBackgroundButton; return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0); }, click: function(element) { this.core.mediaControl.show(); if (element === this.$buttonIcon && this.shouldStop) { this.core.mediaControl.togglePlayStop(); } else if (element !== this.$buttonIcon && !this.shouldStop) { this.core.mediaControl.togglePlayPause(); } }, show: function() { this.$el.removeClass('hide'); }, hide: function() { this.$el.addClass('hide'); }, enable: function() { this.stopListening(); $traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []); this.$playPauseButton.hide(); this.$playStopButton.hide(); }, disable: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []); this.$playPauseButton.show(); this.$playStopButton.show(); }, playing: function() { this.$buttonIcon.removeClass('notplaying').addClass('playing'); }, notplaying: function() { this.$buttonIcon.removeClass('playing').addClass('notplaying'); }, getExternalInterface: function() {}, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)}); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]'); this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]'); this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]'); this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]'); this.shouldStop = this.$playStopButton.length > 0; this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]')); this.$el.click((function() { return $__0.click($__0.$el); })); this.$buttonIcon.click((function() { return $__0.click($__0.$buttonIcon); })); process.nextTick((function() { return $__0.updateSize(); })); if (this.enabled) { this.$playPauseButton.hide(); this.$playStopButton.hide(); } if (this.shouldStop) { this.$buttonIcon.addClass('playstop'); } else { this.$el.addClass('pointer-enabled'); } if (this.core.mediaControl.isVisible()) { this.show(); } return this; } }, {}, UICorePlugin); module.exports = BackgroundButton; }).call(this,require("FWaASH")) },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_core_plugin":"gNZMEo","../../components/mediator":"veeMMc","../../components/player_info":"Rmed05","FWaASH":1}],58:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":57}],59:[function(require,module,exports){ "use strict"; var UICorePlugin = require('../../base/ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var DVRControls = function DVRControls(core) { $traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $DVRControls = DVRControls; ($traceurRuntime.createClass)(DVRControls, { get template() { return JST.dvr_controls; }, get name() { return 'dvr_controls'; }, get events() { return {'click .live-button': 'click'}; }, get attributes() { return { 'class': 'dvr-controls', 'data-dvr-controls': '' }; }, bindEvents: function() { this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.dvrChanged); }, dvrChanged: function(dvrEnabled) { this.settingsUpdate(); this.core.mediaControl.$el.addClass('live'); if (dvrEnabled) { this.core.mediaControl.$el.addClass('dvr'); } else { this.core.mediaControl.$el.removeClass('dvr'); } }, click: function() { if (!this.core.mediaControl.container.isPlaying()) { this.core.mediaControl.container.play(); } this.core.mediaControl.container.setCurrentTime(-1); }, settingsUpdate: function() { var $__0 = this; this.stopListening(); if (this.shouldRender()) { this.render(); this.$el.click((function() { return $__0.click(); })); } this.bindEvents(); }, shouldRender: function() { var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls; return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live'; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); if (this.shouldRender()) { this.core.mediaControl.$el.addClass('live'); this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el); } return this; } }, {}, UICorePlugin); module.exports = DVRControls; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_core_plugin":"gNZMEo"}],60:[function(require,module,exports){ "use strict"; module.exports = require('./dvr_controls'); },{"./dvr_controls":59}],61:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":62}],62:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var Mousetrap = require('mousetrap'); var BOLD = 'font-weight: bold; font-size: 13px;'; var INFO = 'color: green;' + BOLD; var DEBUG = 'color: #222;' + BOLD; var ERROR = 'color: red;' + BOLD; var DEFAULT = ''; Mousetrap.bind(['ctrl+shift+d'], (function() { return window.DEBUG = !window.DEBUG; })); var Log = function(klass) { this.klass = klass || 'Logger'; }; Log.info = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.error = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; Log.prototype = { log: function(msg) { this.info(msg); }, info: function(msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg); }, error: function(msg) { console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg); } }; module.exports = Log; },{"jquery":3,"mousetrap":4}],63:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":64}],64:[function(require,module,exports){ (function (process){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var PlayerInfo = require('../../components/player_info'); var $ = require('jquery'); var _ = require('underscore'); var PosterPlugin = function PosterPlugin(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]); this.options = options; _.defaults(this.options, {disableControlsOnPoster: true}); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } this.render(); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []); Mediator.off('player:resize', this.updateSize, this); }, onBuffering: function() { this.hidePlayButton(); }, onPlay: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.$playButton.show(); this.updateSize(); }, clicked: function() { this.container.play(); }, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); if (this.$playWrapper.is(':visible')) { this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)}); if (!this.options.hidePlayButton) { this.$playButton.show(); } } else { this.$playButton.hide(); } }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playButton = this.$el.find('.poster-icon'); this.$playWrapper = this.$el.find('.play-wrapper'); if (this.options.poster !== undefined) { var imgEl = $('<img data-poster class="poster-background"></img>'); imgEl.attr('src', this.options.poster); this.$el.prepend(imgEl); } this.container.$el.append(this.el); if (!!this.options.hidePlayButton) { this.hidePlayButton(); } process.nextTick((function() { return $__0.updateSize(); })); return this; } }, {}, UIContainerPlugin); module.exports = PosterPlugin; }).call(this,require("FWaASH")) },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT","../../components/mediator":"veeMMc","../../components/player_info":"Rmed05","FWaASH":1,"jquery":3,"underscore":6}],65:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":66}],66:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST.spinner_three_bounce; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stop', this.onStop); this.render(); }; var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin; ($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, { get name() { return 'spinner'; }, get attributes() { return { 'data-spinner': '', 'class': 'spinner-three-bounce' }; }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.html(this.template()); var style = Styler.getStyleFor('spinner_three_bounce'); this.container.$el.append(style); this.container.$el.append(this.$el); this.$el.hide(); return this; } }, {}, UIContainerPlugin); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}],67:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":68}],68:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('../../base/container_plugin'); var $ = require("jquery"); var StatsPlugin = function StatsPlugin(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, bindEvents: function() { this.listenTo(this.container.playback, 'playback:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd); }, setReportInterval: function(reportInterval) { this.reportInterval = reportInterval; }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); if (!this.intervalId) { this.intervalId = setInterval(this.report.bind(this), this.reportInterval); } }, onStop: function() { clearInterval(this.intervalId); this.intervalId = undefined; this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else if (!!this.rebufferingTimeInit) { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { this.container.statsReport(this.getStats()); } }, {}, ContainerPlugin); module.exports = StatsPlugin; },{"../../base/container_plugin":"6xH8xW","jquery":3}],69:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":70}],70:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var WaterMarkPlugin = function WaterMarkPlugin(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; if (options.watermark) { this.imageUrl = options.watermark; this.render(); } else { this.$el.remove(); } }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIContainerPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}]},{},[2,46])
src/esm/components/feedback/vertical-progress/components/step.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["statusType", "statusProps", "progressTitle", "children"]; import React from 'react'; import styled from 'styled-components'; import { pxToRem } from '../../../../helpers/utils/typography'; import { ScreenConfig } from '../../../../constants/screen-config'; import { Status } from './status'; var StyledItem = styled.li.withConfig({ displayName: "step__StyledItem", componentId: "sc-hcrd93-0" })(["margin:", " 0 ", " 0;display:flex;flex-direction:column;padding-right:", ";&:first-of-type{margin-top:0;padding-top:0;}&:last-of-type{margin-bottom:0;padding-bottom:0;}& li:not(:last-of-type){margin:0 !important;&::after{display:none;}}.k-VerticalProgress__step--content{padding-left:", ";@media (min-width:", "px){padding-left:", ";}}"], pxToRem(15), pxToRem(25), pxToRem(10), pxToRem(50), ScreenConfig.S.min, pxToRem(82)); export var Step = function Step(_ref) { var statusType = _ref.statusType, statusProps = _ref.statusProps, progressTitle = _ref.progressTitle, children = _ref.children, other = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement(StyledItem, _extends({ className: "k-VerticalProgress__item" }, other), /*#__PURE__*/React.createElement(Status, _extends({ statusType: statusType, progressTitle: progressTitle }, statusProps)), /*#__PURE__*/React.createElement("div", { className: "k-VerticalProgress__step--content" }, children)); };
src/utils/domUtils.js
pieter-lazzaro/react-bootstrap
import React from 'react'; let canUseDom = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); /** * Get elements owner document * * @param {ReactComponent|HTMLElement} componentOrElement * @returns {HTMLElement} */ function ownerDocument(componentOrElement) { let elem = React.findDOMNode(componentOrElement); return (elem && elem.ownerDocument) || document; } function ownerWindow(componentOrElement) { let doc = ownerDocument(componentOrElement); return doc.defaultView ? doc.defaultView : doc.parentWindow; } /** * get the active element, safe in IE * @return {HTMLElement} */ function getActiveElement(componentOrElement){ let doc = ownerDocument(componentOrElement); try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } /** * Shortcut to compute element style * * @param {HTMLElement} elem * @returns {CssStyle} */ function getComputedStyles(elem) { return ownerDocument(elem).defaultView.getComputedStyle(elem, null); } /** * Get elements offset * * TODO: REMOVE JQUERY! * * @param {HTMLElement} DOMNode * @returns {{top: number, left: number}} */ function getOffset(DOMNode) { if (window.jQuery) { return window.jQuery(DOMNode).offset(); } let docElem = ownerDocument(DOMNode).documentElement; let box = { top: 0, left: 0 }; // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof DOMNode.getBoundingClientRect !== 'undefined' ) { box = DOMNode.getBoundingClientRect(); } return { top: box.top + window.pageYOffset - docElem.clientTop, left: box.left + window.pageXOffset - docElem.clientLeft }; } /** * Get elements position * * TODO: REMOVE JQUERY! * * @param {HTMLElement} elem * @param {HTMLElement?} offsetParent * @returns {{top: number, left: number}} */ function getPosition(elem, offsetParent) { let offset, parentOffset; if (window.jQuery) { if (!offsetParent) { return window.jQuery(elem).position(); } offset = window.jQuery(elem).offset(); parentOffset = window.jQuery(offsetParent).offset(); // Get element offset relative to offsetParent return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } parentOffset = {top: 0, left: 0}; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (getComputedStyles(elem).position === 'fixed' ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = offsetParentFunc(elem); } // Get correct offsets offset = getOffset(elem); if ( offsetParent.nodeName !== 'HTML') { parentOffset = getOffset(offsetParent); } // Add offsetParent borders parentOffset.top += parseInt(getComputedStyles(offsetParent).borderTopWidth, 10); parentOffset.left += parseInt(getComputedStyles(offsetParent).borderLeftWidth, 10); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(getComputedStyles(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(getComputedStyles(elem).marginLeft, 10) }; } /** * Get an element's size * * @param {HTMLElement} elem * @returns {{width: number, height: number}} */ function getSize(elem) { let rect = { width: elem.offsetWidth || 0, height: elem.offsetHeight || 0 }; if (typeof elem.getBoundingClientRect !== 'undefined') { let {width, height} = elem.getBoundingClientRect(); rect.width = width || rect.width; rect.height = height || rect.height; } return rect; } /** * Get parent element * * @param {HTMLElement?} elem * @returns {HTMLElement} */ function offsetParentFunc(elem) { let docElem = ownerDocument(elem).documentElement; let offsetParent = elem.offsetParent || docElem; while ( offsetParent && ( offsetParent.nodeName !== 'HTML' && getComputedStyles(offsetParent).position === 'static' ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; } /** * Cross browser .contains() polyfill * @param {HTMLElement} elem * @param {HTMLElement} inner * @return {bool} */ function contains(elem, inner){ function ie8Contains(root, node) { while (node) { if (node === root) { return true; } node = node.parentNode; } return false; } return (elem && elem.contains) ? elem.contains(inner) : (elem && elem.compareDocumentPosition) ? elem === inner || !!(elem.compareDocumentPosition(inner) & 16) : ie8Contains(elem, inner); } export default { canUseDom, contains, ownerWindow, ownerDocument, getComputedStyles, getOffset, getPosition, getSize, activeElement: getActiveElement, offsetParent: offsetParentFunc };
src/uic/RangeSelector.js
ajaycheenath/earthquake
import React, { Component } from 'react'; import rangeStyle from "../css/range.css"; class RangeSelector extends Component { static propTypes = { start: React.PropTypes.number, end: React.PropTypes.number, selectedRange: React.PropTypes.number, onClick: React.PropTypes.func }; render() { const {start, end, selectedRange, onClick} = this.props; const range = []; for(let i = start ; i <= end; i++) { const selected = selectedRange === i ? "selected" : ""; range.push(<span key={i} className={rangeStyle.numberCircle + " " + rangeStyle[selected]} onClick={(event) => onClick(i)}>{i}</span>); } return(<div>{range}</div>); } } export default RangeSelector;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
rohit-sourcefuse/mxtr-theme
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/frontend/components/survey-renderers/BSDSurvey.js
al3x/ground-control
import React from 'react'; import Relay from 'react-relay'; import Radium from 'radium'; import {LinearProgress} from 'material-ui'; // This just handles rendering and interacting with a BSD survey in an iFrame @Radium class BSDSurvey extends React.Component { styles = { container: { // width: '100%', }, progress: { width: '50%', marginLeft: 'auto', marginRight: 'auto', marginTop: '30px', marginBottom: '30px', textAlign: 'center', }, progressHeader: { marginBottom: '10px', }, frame: { display: 'block', border: 'none', width: '100%', height: 0, opacity: 0, transition: 'opacity 0.7s', } } static propTypes = { onSubmitted : React.PropTypes.func, } state = { frameStyle : {height: 0}, surveyFields: {}, cacheBreakValue: Math.random().toString(36).substring(7) } submit = () => { this.sendFrameMessage({message: 'getFieldValues'}) } setFieldValue(fieldId, value) { this.sendFrameMessage({ message: 'setInputValue', details: { inputId: fieldId, value: value }}) } frameMessageHandler = (event) => { if (event.origin !== this.frameHost()) return; if (event.data.message == 'documentLoaded') { if (event.data.details.location.indexOf(this.props.survey.fullURL) !== -1) { this.sendFrameMessage({ message: 'setInputValue', details: { inputId: 'email', value: this.props.interviewee.email }}) this.sendFrameMessage({message: 'getHeight'}); } else { this.props.onSubmitted(this.state.surveyFields); } } else if (event.data.message === 'fieldValues') { console.log('got field values') this.setState({surveyFields: event.data.details}) this.sendFrameMessage({message: 'submit'}) } else if (event.data.message == 'documentHeight') { console.log('got height', event.data.details.height) this.setState({ frameStyle: { height: event.data.details.height, opacity: '1', }, loadingStyle: { display: 'none', } }) } } sendFrameMessage(message) { this.refs.frame.contentWindow.postMessage(message, this.frameHost()) } componentDidMount() { window.addEventListener('message', this.frameMessageHandler) } componentWillUnmount() { window.removeEventListener('message', this.frameMessageHandler); } hostFromURLString(URLString) { return URLString.split('/').slice(0, 3).join('/'); } frameHost() { return this.hostFromURLString(this.props.survey.fullURL); } render() { let cacheBreak = '?cacheBreak=' + this.state.cacheBreakValue; let source = this.props.survey.fullURL + cacheBreak; let loading = ( <div style={[this.styles.progress, this.state.loadingStyle]}> <h3 style={this.styles.progressHeader}>Loading survey...</h3> <LinearProgress mode="indeterminate" /> </div> ) let frame = ( <iframe ref='frame' scrolling='no' src={source} style={[this.styles.frame, this.state.frameStyle]} onLoad={this.frameLoaded} /> ) return ( <div style={this.styles.container}> {loading} {frame} </div> ) } } export default Relay.createContainer(BSDSurvey, { fragments: { survey: () => Relay.QL` fragment on Survey { fullURL } `, interviewee: () => Relay.QL` fragment on Person { email } ` } })
src/components/idle.js
whoisandie/react-player
import React from 'react'; import cx from 'classnames'; import Player from '../player'; const { PropTypes, Component } = React; class Idle extends Component { static propTypes = { playing: PropTypes.bool, player: PropTypes.instanceOf(Player), className: PropTypes.string, } shouldComponentUpdate() { return false; } handleClick = () => { let { playing, player } = this.props; if (!playing) { player && player.play(); } else { player && player.pause(); } } render() { let { className } = this.props; const classNames = cx('rp-idle', className); return ( <div className={classNames} onClick={this.handleClick} /> ); } } export default Idle;
src/svg-icons/action/cached.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCached = (props) => ( <SvgIcon {...props}> <path d="M19 8l-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.43 20 12 20c4.42 0 8-3.58 8-8h3l-4-4zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.57 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4H6z"/> </SvgIcon> ); ActionCached = pure(ActionCached); ActionCached.displayName = 'ActionCached'; ActionCached.muiName = 'SvgIcon'; export default ActionCached;
packages/material-ui-icons/src/WifiLockOutlined.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 d="M21.31 9.58L24 6c-3.34-2.51-7.5-4-12-4S3.34 3.49 0 6l12 16 3.5-4.67V14.5c0-2.76 2.24-5 5-5 .28 0 .55.04.81.08z" /><path d="M23 16v-1.5c0-1.38-1.12-2.5-2.5-2.5S18 13.12 18 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z" /></g></React.Fragment> , 'WifiLockOutlined');
information/blendle-frontend-react-source/app/modules/overlay/module.js
BramscoChill/BlendleParser
import React from 'react'; import PremiumVerifiedOverlayContainer from 'containers/overlays/PremiumVerifiedOverlayContainer'; export function openPremiumSuccess(dismissRoute) { return <PremiumVerifiedOverlayContainer dismissRoute={dismissRoute} />; } // WEBPACK FOOTER // // ./src/js/app/modules/overlay/module.js
webapp/app/components/SoftwaresByUser/Table/ModalUpdateSoftware/index.js
EIP-SAM/SAM-Solution-Node-js
// // Modal to update a software in softwares by user page // import React from 'react'; import { Modal, ButtonToolbar, Glyphicon } from 'react-bootstrap'; import LinkContainerButton from 'components/Button'; import styles from 'components/SoftwaresByUser/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class SoftwaresByUserUpdateSoftwareModal extends React.Component { handleUpdateClick() { this.props.hideUpdateSoftwareModal(); this.props.updateSoftwares(this.props.username, this.props.softName); this.props.resetStateTable(); } render() { return ( <Modal show={this.props.showModal} onHide={this.props.hideUpdateSoftwareModal}> <Modal.Header closeButton> <Modal.Title><Glyphicon glyph="open" className={styles.iconUpdate} />Update software</Modal.Title> </Modal.Header> <Modal.Body className={styles.p}> <p>You are about to update the software <span className={styles.bold}>{this.props.softName}</span>.</p> <p className={styles.bold}>Are you sure that you want to update it?</p> </Modal.Body> <Modal.Footer> <ButtonToolbar> <LinkContainerButton buttonBsStyle="warning" buttonText="Update" onClick={() => this.handleUpdateClick()} /> <LinkContainerButton buttonBsStyle="default" buttonText="Cancel" onClick={this.props.hideUpdateSoftwareModal} /> </ButtonToolbar> </Modal.Footer> </Modal> ); } } SoftwaresByUserUpdateSoftwareModal.propTypes = { username: React.PropTypes.string, softName: React.PropTypes.string, showModal: React.PropTypes.bool, hideUpdateSoftwareModal: React.PropTypes.func, updateSoftwares: React.PropTypes.func, resetStateTable: React.PropTypes.func, };
packager/react-packager/src/Server/index.js
dirkliu/react-native
/** * Copyright (c) 2015-present, 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. */ 'use strict'; var url = require('url'); var path = require('path'); var declareOpts = require('../lib/declareOpts'); var FileWatcher = require('../FileWatcher'); var Packager = require('../Packager'); var Activity = require('../Activity'); var q = require('q'); var _ = require('underscore'); module.exports = Server; var validateOpts = declareOpts({ projectRoots: { type: 'array', required: true, }, blacklistRE: { type: 'object', // typeof regex is object }, moduleFormat: { type: 'string', default: 'haste', }, polyfillModuleNames: { type: 'array', default: [], }, cacheVersion: { type: 'string', default: '1.0', }, resetCache: { type: 'boolean', default: false, }, transformModulePath: { type:'string', required: false, }, nonPersistent: { type: 'boolean', default: false, }, assetRoots: { type: 'array', required: false, }, assetExts: { type: 'array', default: ['png'], }, }); function Server(options) { var opts = validateOpts(options); this._projectRoots = opts.projectRoots; this._packages = Object.create(null); this._changeWatchers = []; var watchRootConfigs = opts.projectRoots.map(function(dir) { return { dir: dir, globs: [ '**/*.js', '**/package.json', ] }; }); if (opts.assetRoots != null) { watchRootConfigs = watchRootConfigs.concat( opts.assetRoots.map(function(dir) { return { dir: dir, globs: opts.assetExts.map(function(ext) { return '**/*.' + ext; }), }; }) ); } this._fileWatcher = options.nonPersistent ? FileWatcher.createDummyWatcher() : new FileWatcher(watchRootConfigs); var packagerOpts = Object.create(opts); packagerOpts.fileWatcher = this._fileWatcher; this._packager = new Packager(packagerOpts); var onFileChange = this._onFileChange.bind(this); this._fileWatcher.on('all', onFileChange); var self = this; this._debouncedFileChangeHandler = _.debounce(function(filePath) { self._rebuildPackages(filePath); self._informChangeWatchers(); }, 50); } Server.prototype._onFileChange = function(type, filepath, root) { var absPath = path.join(root, filepath); this._packager.invalidateFile(absPath); // Make sure the file watcher event runs through the system before // we rebuild the packages. this._debouncedFileChangeHandler(absPath); }; Server.prototype._rebuildPackages = function() { var buildPackage = this._buildPackage.bind(this); var packages = this._packages; Object.keys(packages).forEach(function(key) { var options = getOptionsFromUrl(key); // Wait for a previous build (if exists) to finish. packages[key] = (packages[key] || q()).finally(function() { // With finally promise callback we can't change the state of the promise // so we need to reassign the promise. packages[key] = buildPackage(options).then(function(p) { // Make a throwaway call to getSource to cache the source string. p.getSource({ inlineSourceMap: options.inlineSourceMap, minify: options.minify, }); return p; }); }); return packages[key]; }); }; Server.prototype._informChangeWatchers = function() { var watchers = this._changeWatchers; var headers = { 'Content-Type': 'application/json; charset=UTF-8', }; watchers.forEach(function(w) { w.res.writeHead(205, headers); w.res.end(JSON.stringify({ changed: true })); }); this._changeWatchers = []; }; Server.prototype.end = function() { q.all([ this._fileWatcher.end(), this._packager.kill(), ]); }; Server.prototype._buildPackage = function(options) { return this._packager.package( options.main, options.runModule, options.sourceMapUrl, options.dev ); }; Server.prototype.buildPackageFromUrl = function(reqUrl) { var options = getOptionsFromUrl(reqUrl); return this._buildPackage(options); }; Server.prototype.getDependencies = function(main) { return this._packager.getDependencies(main); }; Server.prototype._processDebugRequest = function(reqUrl, res) { var ret = '<!doctype html>'; var pathname = url.parse(reqUrl).pathname; var parts = pathname.split('/').filter(Boolean); if (parts.length === 1) { ret += '<div><a href="/debug/packages">Cached Packages</a></div>'; ret += '<div><a href="/debug/graph">Dependency Graph</a></div>'; res.end(ret); } else if (parts[1] === 'packages') { ret += '<h1> Cached Packages </h1>'; q.all(Object.keys(this._packages).map(function(url) { return this._packages[url].then(function(p) { ret += '<div><h2>' + url + '</h2>'; ret += p.getDebugInfo(); }); }, this)).then( function() { res.end(ret); }, function(e) { res.wrteHead(500); res.end('Internal Error'); console.log(e.stack); } ); } else if (parts[1] === 'graph'){ ret += '<h1> Dependency Graph </h2>'; ret += this._packager.getGraphDebugInfo(); res.end(ret); } else { res.writeHead('404'); res.end('Invalid debug request'); return; } }; Server.prototype._processOnChangeRequest = function(req, res) { var watchers = this._changeWatchers; watchers.push({ req: req, res: res, }); req.on('close', function() { for (var i = 0; i < watchers.length; i++) { if (watchers[i] && watchers[i].req === req) { watchers.splice(i, 1); break; } } }); }; Server.prototype.processRequest = function(req, res, next) { var urlObj = url.parse(req.url, true); var pathname = urlObj.pathname; var requestType; if (pathname.match(/\.bundle$/)) { requestType = 'bundle'; } else if (pathname.match(/\.map$/)) { requestType = 'map'; } else if (pathname.match(/^\/debug/)) { this._processDebugRequest(req.url, res); return; } else if (pathname.match(/^\/onchange\/?$/)) { this._processOnChangeRequest(req, res); return; } else { next(); return; } var startReqEventId = Activity.startEvent('request:' + req.url); var options = getOptionsFromUrl(req.url); var building = this._packages[req.url] || this._buildPackage(options); this._packages[req.url] = building; building.then( function(p) { if (requestType === 'bundle') { res.end(p.getSource({ inlineSourceMap: options.inlineSourceMap, minify: options.minify, })); Activity.endEvent(startReqEventId); } else if (requestType === 'map') { res.end(JSON.stringify(p.getSourceMap())); Activity.endEvent(startReqEventId); } }, function(error) { handleError(res, error); } ).done(); }; function getOptionsFromUrl(reqUrl) { // `true` to parse the query param as an object. var urlObj = url.parse(reqUrl, true); // node v0.11.14 bug see https://github.com/facebook/react-native/issues/218 urlObj.query = urlObj.query || {}; var pathname = urlObj.pathname; // Backwards compatibility. Options used to be as added as '.' to the // entry module name. We can safely remove these options. var entryFile = pathname.replace(/^\//, '').split('.').filter(function(part) { if (part === 'includeRequire' || part === 'runModule' || part === 'bundle' || part === 'map') { return false; } return true; }).join('.') + '.js'; return { sourceMapUrl: pathname.replace(/\.bundle$/, '.map'), main: entryFile, dev: getBoolOptionFromQuery(urlObj.query, 'dev', true), minify: getBoolOptionFromQuery(urlObj.query, 'minify'), runModule: getBoolOptionFromQuery(urlObj.query, 'runModule', true), inlineSourceMap: getBoolOptionFromQuery( urlObj.query, 'inlineSourceMap', false ), }; } function getBoolOptionFromQuery(query, opt, defaultVal) { if (query[opt] == null && defaultVal != null) { return defaultVal; } return query[opt] === 'true' || query[opt] === '1'; } function handleError(res, error) { res.writeHead(error.status || 500, { 'Content-Type': 'application/json; charset=UTF-8', }); if (error.type === 'TransformError' || error.type === 'NotFoundError') { res.end(JSON.stringify(error)); } else { console.error(error.stack || error); res.end(JSON.stringify({ type: 'InternalError', message: 'react-packager has encountered an internal error, ' + 'please check your terminal error output for more details', })); } }
src/routes.js
NoobJS-nwhax/nwhacks-2017
'use strict'; import React from 'react' import { Route, IndexRoute } from 'react-router' import Layout from './components/Layout'; import IndexPage from './components/IndexPage'; import AthletePage from './components/AthletePage'; import CreateSpacePage from './components/CreateSpacePage'; import NotFoundPage from './components/NotFoundPage'; const routes = ( <Route path="/" component={Layout}> <IndexRoute component={IndexPage}/> <Route path="athlete/:id" component={AthletePage}/> <Route path="create-space" component={CreateSpacePage}/> <Route path="*" component={NotFoundPage}/> </Route> ); export default routes;
src/svg-icons/image/exposure-neg-2.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageExposureNeg2 = (props) => ( <SvgIcon {...props}> <path d="M15.05 16.29l2.86-3.07c.38-.39.72-.79 1.04-1.18.32-.39.59-.78.82-1.17.23-.39.41-.78.54-1.17s.19-.79.19-1.18c0-.53-.09-1.02-.27-1.46-.18-.44-.44-.81-.78-1.11-.34-.31-.77-.54-1.26-.71-.51-.16-1.08-.24-1.72-.24-.69 0-1.31.11-1.85.32-.54.21-1 .51-1.36.88-.37.37-.65.8-.84 1.3-.18.47-.27.97-.28 1.5h2.14c.01-.31.05-.6.13-.87.09-.29.23-.54.4-.75.18-.21.41-.37.68-.49.27-.12.6-.18.96-.18.31 0 .58.05.81.15.23.1.43.25.59.43.16.18.28.4.37.65.08.25.13.52.13.81 0 .22-.03.43-.08.65-.06.22-.15.45-.29.7-.14.25-.32.53-.56.83-.23.3-.52.65-.88 1.03l-4.17 4.55V18H21v-1.71h-5.95zM2 11v2h8v-2H2z"/> </SvgIcon> ); ImageExposureNeg2 = pure(ImageExposureNeg2); ImageExposureNeg2.displayName = 'ImageExposureNeg2'; ImageExposureNeg2.muiName = 'SvgIcon'; export default ImageExposureNeg2;
jenkins-design-language/src/js/components/material-ui/svg-icons/places/all-inclusive.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const PlacesAllInclusive = (props) => ( <SvgIcon {...props}> <path d="M18.6 6.62c-1.44 0-2.8.56-3.77 1.53L12 10.66 10.48 12h.01L7.8 14.39c-.64.64-1.49.99-2.4.99-1.87 0-3.39-1.51-3.39-3.38S3.53 8.62 5.4 8.62c.91 0 1.76.35 2.44 1.03l1.13 1 1.51-1.34L9.22 8.2C8.2 7.18 6.84 6.62 5.4 6.62 2.42 6.62 0 9.04 0 12s2.42 5.38 5.4 5.38c1.44 0 2.8-.56 3.77-1.53l2.83-2.5.01.01L13.52 12h-.01l2.69-2.39c.64-.64 1.49-.99 2.4-.99 1.87 0 3.39 1.51 3.39 3.38s-1.52 3.38-3.39 3.38c-.9 0-1.76-.35-2.44-1.03l-1.14-1.01-1.51 1.34 1.27 1.12c1.02 1.01 2.37 1.57 3.82 1.57 2.98 0 5.4-2.41 5.4-5.38s-2.42-5.37-5.4-5.37z"/> </SvgIcon> ); PlacesAllInclusive.displayName = 'PlacesAllInclusive'; PlacesAllInclusive.muiName = 'SvgIcon'; export default PlacesAllInclusive;
components/App.js
owennicol/yaiza
// React import React from 'react'; // Prismic import Prismic from 'prismic.io'; // Config import config from '../config/config'; // Components import ExecutionEnvironment from 'exenv'; import Header from '../components/Header/Header'; import Nav from './Nav' import Footer from '../components/Footer'; Array.prototype.findIndex = Array.prototype.findIndex || function (evaluator, thisArg) { 'use strict'; if (!this) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof (evaluator) !== 'function') { if (typeof (evaluator) === 'string') { // Attempt to convert it to a function if (!(evaluator = eval(evaluator))) { throw new TypeError(); } } else { throw new TypeError(); } } var i; if (thisArg === undefined) { // Optimize for thisArg for (i in this) { if (evaluator(this[i], i, this)) { return i; } } return -1; } for (i in this) { if (evaluator.call(thisArg, this[i], i, this)) { return i; } } return -1; }; let MobileDetect = require('mobile-detect'); let md; if (typeof window !== 'undefined') { md = new MobileDetect(window.navigator.userAgent); } if (process.env.APP_ENV === 'browser') { // Styles require('../styles/index.scss'); } class App extends React.Component { constructor() { super(); this.state = { hasLoaded: false, menuIsOpen: false, headerIsActive: false, currentPage: '', isYoutubeVideoPlaying: false, homepageSlide: 0, headerHeight: 70 }; this.getPrismicData = this.getPrismicData.bind(this); this.setPrismicData = this.setPrismicData.bind(this); this.getProjects = this.getProjects.bind(this); this.getProjectOverview = this.getProjectOverview.bind(this); this.getHomePageContent = this.getHomePageContent.bind(this); this.handleHideSplash = this.handleHideSplash.bind(this); this.handleToggleMenu = this.handleToggleMenu.bind(this); this.handleToggleYoutubeVideo = this.handleToggleYoutubeVideo.bind(this); this.handleSetHomepageSlide = this.handleSetHomepageSlide.bind(this); this.handleScroll = this.handleScroll.bind(this); } componentWillMount() { this.getPrismicData(this.query); } componentDidMount() { if (ExecutionEnvironment.canUseDOM){ document.addEventListener("contextmenu", function(e){ e.preventDefault(); }, false) if (!this.props.mobile) { window.addEventListener('scroll', this.handleScroll); } } } componentWillUnmount() { if (ExecutionEnvironment.canUseDOM && !this.props.mobile) { window.removeEventListener('scroll', this.handleScroll); } } handleScroll(event) { let scrollTop = event.srcElement.body.scrollTop; if (scrollTop > this.state.headerHeight) { this.setState({headerIsActive: true}); } else { this.setState({headerIsActive: false}); } } getProjectOverview(data) { this.setState({ projectOverview: data .filter(doc => doc.type === 'project-overview') }); } getProjects(data) { this.setState({ projects: data .filter(doc => doc.type === 'casestudy') .sort(function (a, b) { return a.fragments["casestudy.navigation-order"] && b.fragments["casestudy.navigation-order"] && a.fragments["casestudy.navigation-order"].value - b.fragments["casestudy.navigation-order"].value }) }); } getHomePageContent(data) { const homepageDoc = data.find(doc => doc.type === 'homepage') const description = homepageDoc.fragments['homepage.meta-description'].asText() const keywords = homepageDoc.fragments['homepage.meta-keywords'].asText() this.setState({ homepageContent: data.filter(doc => doc.tags.find(tag => 'homepage')), homepageMeta: { description, keywords, } }); } setPrismicData(data) { this.getProjects(data); this.getProjectOverview(data); this.getHomePageContent(data); this.setState({ hasLoaded: true }); } handleHideSplash() { this.setState({ hideSplash: true }); } handleToggleMenu(e) { e.preventDefault(); this.setState({ menuIsOpen: !this.state.menuIsOpen }) } handleToggleYoutubeVideo(isVideoPlaying) { this.setState({ isYoutubeVideoPlaying: isVideoPlaying }) } handleSetHomepageSlide(index) { this.setState({ homepageSlide: index }); } getPrismicData(query) { Prismic.api(config.apiURL).then((api) => { return api.query(''); }).then((response) => { return this.setPrismicData(response.results); }, (err) => { console.log('Something went wrong: ', err); }); } render() { const childrenWithProps = React.Children.map(this.props.children, (child) => React.cloneElement(child, { projects: this.state.projects, projectOverview: this.state.projectOverview, homepageContent: this.state.homepageContent, homepageMeta: this.state.homepageMeta, setHomepageSlide: this.handleSetHomepageSlide, homepageSlide: this.state.homepageSlide, hasLoaded: this.state.hasLoaded, handleHideSplash: this.handleHideSplash, hideSplash: this.state.hideSplash, toggleYoutubeVideo: this.handleToggleYoutubeVideo, isYoutubeVideoPlaying: this.state.isYoutubeVideoPlaying, videoURL: config.videoURL, mobile: md && md.mobile(), headerHeight: this.state.headerHeight }) ); return ( <div id="wrapper"> {this.state.hasLoaded && <Header toggleMenu={this.handleToggleMenu} menuIsOpen={this.state.menuIsOpen} headerIsActive={this.state.headerIsActive} projects={this.state.projects} pathname={this.props.location.pathname} headerHeight={this.state.headerHeight} /> } {this.state.hasLoaded && <Nav toggleMenu={this.handleToggleMenu} menuIsOpen={this.state.menuIsOpen} projects={this.state.projects} pathname={this.props.location.pathname} /> } {childrenWithProps} {this.state.hasLoaded && this.props.location.pathname !== '/' && <Footer /> } </div> ); } } export default App
gulpfile.js
rpoli/mindScoper
//*********** IMPORTS *****************// var gulp = require('gulp'), sass = require('gulp-ruby-sass'), minifycss = require('gulp-minify-css'), cssBase64 = require('gulp-css-base64'), gutil = require('gulp-util'), rename = require("gulp-rename"), map = require("map-stream"), livereload = require("gulp-livereload"), concat = require("gulp-concat"), uglify = require('gulp-uglify'), watch = require('gulp-watch'), gulpIgnore = require('gulp-ignore'), concatCss = require('gulp-concat-css'), gulpCopy = require('gulp-copy'), autoprefixer = require('gulp-autoprefixer'), connect = require('gulp-connect'), clean = require('gulp-clean'), browserSync = require('browser-sync').create(), sourcemaps = require('gulp-sourcemaps'), add = require('gulp-add'), browserify = require('browserify'), vsource = require('vinyl-source-stream'), buffer = require('vinyl-buffer'), babelify = require('babelify'); open = require('gulp-open'), gls = require('gulp-live-server'), watchify = require('watchify'), csv2json = require('gulp-csv2json'); var env = process.env.NODE_ENV || 'development', gConfig = require("./config/gulpConfig_"+env); var gServer = gls.new('app.js'), serverPromise; global.errorMessage = ''; //build datestamp for cache busting var getStamp = function() { var stampDate = new Date(); var stampYear = stampDate.getFullYear().toString(); var stampMonth = ('0' + (stampDate.getMonth() + 1)).slice(-2); var stampDay = ('0' + stampDate.getDate()).slice(-2); var stampSeconds = stampDate.getSeconds().toString(); var stampFullDate = stampYear + stampMonth + stampDay + stampSeconds; return stampFullDate; }; var sassConfig = [{ watch: 'public/src/scss/**/*.scss', paths: ['public/src/scss/app-main.scss', 'public/src/scss/webfonts/**.scss'], output: 'public/dist/css/', name: 'app-main.css', excludedFiles: 'public/src/css/webfonts/**.scss', compileOptions: { 'style': 'expanded', // expanded compressed 'unixNewlines': true, 'cacheLocation': './.sass_cache', 'sourcemap': true } }]; var filePaths = { src: 'public/src', dist: 'public/dist/', js: ['scripts/**/*.js', '!scripts/libs/**/*.js'], libs: ['public/src/js/lib/**/*.js'], libsTarget: 'public/dist/js/lib/', styles: ['styles/**/*.css'], views: "public/src/views/layouts/index.html", viewsTarget: "public/dist/", images: "public/src/images/**/**", imagesTarget: "public/dist/images/", fonts: "public/src/fonts/**/**", fontsTarget: "public/dist/fonts/", extras: ['crossdomain.xml', 'humans.txt', 'manifest.appcache', 'robots.txt', 'favicon.ico'] }; gulp.task('clean', function() { return gulp.src(filePaths.dist) .pipe(clean()); }); gulp.task("copysource",function() { console.log("build started"); gulp.src(filePaths.images) .pipe(gulp.dest(filePaths.imagesTarget)); gulp.src(filePaths.fonts) .pipe(gulp.dest(filePaths.fontsTarget)); }) gulp.task('sass', function() { return sass(sassConfig[0].paths[0], sassConfig[0].compileOptions) .on('error', sass.logError) .pipe(sourcemaps.write()) .pipe(cssBase64({ baseDir: "./public", maxWeightResource: 1000000 })) .pipe(gulp.dest(sassConfig[0].output)) }); gulp.task('json', function () { var csvParseOptions = {}; //based on options specified here : http://csv.adaltas.com/parse/ gulp.src('./data/csv/**/*.csv') .pipe(csv2json(csvParseOptions)) .pipe(rename({extname: '.json'})) .pipe(gulp.dest('./data/json/')); }); gulp.task('server', function() { var serverPromise = gServer.start(); serverPromise.then(function(){ }); /*Available app options*/ /*'google-chrome' // Linux 'chrome' // Windows 'google chrome' or 'Google Chrome' // OSX 'firefox'*/ gulp.src('./public/views/layouts/index.html') .pipe(open({ uri: 'http://localhost:'+gConfig.port, app: gConfig.browser || 'chrome' })); gulp.watch(['./public/views/**/*.html','./public/dist/css/**/*.css','./public/dist/js/**/*.js'],function(file){ gServer.notify.call(gServer, file); }); gulp.watch('app.js', function() { gServer.start.bind(gServer)() }); }); /*****Browserify task module*****/ var browserifyHandler = function() { return browserify( { entries: 'public/src/js/main.jsx', extensions: ['.jsx','.js'], debug: true, compact: false, cache: {}, packageCache: {}, paths : ["public/src/js"] }) .transform(babelify, { presets : ["es2015",'stage-0',"react"] }); }; var watchifyHandler = watchify(browserifyHandler()); watchifyHandler.on('log', gutil.log); function bundle(pkg) { return pkg.bundle() .on('error', function(err) { console.error(err); this.emit('end'); }) .pipe(vsource('bundleApp.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./public/dist/js')); } gulp.task("browserify", bundle.bind(null, browserifyHandler())); gulp.task('watch', function () { gulp.watch(['./public/src/scss/**/*.scss'], ['sass']); bundle(watchifyHandler); watchifyHandler.on('update', bundle.bind(null, watchifyHandler)); console.log("Listening to Scss, Script changes"); }); gulp.task("build", [ "copysource","sass","browserify"]); gulp.task("default", [ "copysource","sass","browserify"]);
src/components/NewsContainer.js
radubrehar/evanghelic.ro
import React from 'react'; import Link from 'gatsby-link'; import moment from 'moment'; import nl2br from 'nl2br'; import Text from '@app/Text'; import Card from '@app/Card'; import { accentColor } from '@app/colors'; moment.locale('ro'); export default ({ news }) => ( <div className="container-fluid" css={{ background: accentColor }}> <div className="container"> <div className="row" style={{ paddingBottom: 20, paddingTop: 20, marginBottom: 20 }} > {news.map(article => { const ago = moment(article.date).fromNow(); return ( <div key={article.url} className="col-12 col-md-6"> <Card className="col-12" title={article.title} subtitle={`Publicat: ${ago}.`} actions={[ <Link key={article.url} to={article.url}> Citește mai mult </Link> ]} children={ <div dangerouslySetInnerHTML={{ __html: article.summary }} /> } /> </div> ); })} </div> </div> </div> );
client/src/components/about_page/AboutPage.js
thewizardplusplus/vk-group-stats
import React from 'react' import {AdditionalBlock} from '../additional_block/AdditionalBlock' import {Card, CardHeader, CardText} from 'material-ui/Card' import Icon from '../icon/Icon' import Avatar from 'material-ui/Avatar' export default class AboutPage extends React.Component { render() { return <AdditionalBlock> <Card> <CardHeader avatar={<Avatar icon={<Icon name="info_outline" />} />} title="О сервисе" /> <CardText> <p> <strong>VK Group Stats, v1.1.0</strong> </p> <p> Copyright &copy; 2017 thewizardplusplus </p> </CardText> </Card> </AdditionalBlock> } }
js/jquery-1.11.0.js
genixers/genixers.github.io
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
src/scripts/components/colour/History.js
arkon/ColourNTP
import React from 'react'; import Colours from '../../modules/colours'; import Saved from '../../modules/saved'; export default class History extends React.Component { static defaultProps = { max: 10 }; constructor(props) { super(props); this.state = { history: new Array(this.props.max) }; this.pushToStack = this.pushToStack.bind(this); } componentWillMount() { this.pushToStack(this.props.colour); } componentWillReceiveProps(nextProps) { this.pushToStack(nextProps.colour); } pushToStack(item) { if (item !== this.state.history[this.state.history.length - 1]) { let stack = this.state.history; stack.push(item); // Only keep newest max amount of items stack.splice(0, stack.length - this.props.max); } } render() { return ( <div className="history"> { this.state.history.map((colour, i) => { const formattedColour = Colours.format(colour, this.props.format); return ( <div key={i} className="history__item copy" style={{ backgroundColor: colour }} data-colour={formattedColour} data-clipboard-text={formattedColour} onClick={() => Saved.add(colour)} /> ); }) } </div> ); } }
node_modules/react-bootstrap/es/DropdownToggle.js
WatkinsSoftwareDevelopment/HowardsBarberShop
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 React from 'react'; import classNames from 'classnames'; import Button from './Button'; import SafeAnchor from './SafeAnchor'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; var propTypes = { noCaret: React.PropTypes.bool, open: React.PropTypes.bool, title: React.PropTypes.string, useAnchor: React.PropTypes.bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = function (_React$Component) { _inherits(DropdownToggle, _React$Component); function DropdownToggle() { _classCallCheck(this, DropdownToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DropdownToggle.prototype.render = function render() { var _props = this.props, noCaret = _props.noCaret, open = _props.open, useAnchor = _props.useAnchor, bsClass = _props.bsClass, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? SafeAnchor : Button; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return React.createElement( Component, _extends({}, props, { role: 'button', className: classNames(className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && React.createElement('span', { className: 'caret' }) ); }; return DropdownToggle; }(React.Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; export default setBsClass('dropdown-toggle', DropdownToggle);
src/shared/views/demos/ThreeD/ThreeD.js
in-depth/indepth-demo
import React from 'react' import { Model3d } from '../../plugins/Model3d' const ThreeD = () => { return ( <div> <Model3d url="https://sketchfab.com/models/522e811044bc4e09bf84431e6c1cc109/embed" /> </div> ) } export default ThreeD
docs/src/app/components/pages/components/RefreshIndicator/ExampleReady.js
ichiohta/material-ui
import React from 'react'; import RefreshIndicator from 'material-ui/RefreshIndicator'; const style = { container: { position: 'relative', }, refresh: { display: 'inline-block', position: 'relative', }, }; const RefreshIndicatorExampleSimple = () => ( <div style={style.container}> <RefreshIndicator percentage={30} size={40} left={10} top={0} status="ready" style={style.refresh} /> <RefreshIndicator percentage={60} size={50} left={65} top={0} status="ready" style={style.refresh} /> <RefreshIndicator percentage={80} size={60} left={120} top={0} color="red" status="ready" style={style.refresh} /> <RefreshIndicator percentage={100} size={70} left={175} top={0} color="red" // Overridden by percentage={100} status="ready" style={style.refresh} /> </div> ); export default RefreshIndicatorExampleSimple;
ajax/libs/yui/3.14.0/datatable-core/datatable-core-debug.js
artch/cdnjs
YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ Table = Y.namespace('DataTable').Core = function () {}; Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { var col, columns, i, len, cols; if (isObject(name) && !isArray(name)) { if (name instanceof Y.Node) { col = this.body.getColumn(name); } else { col = name; } } else { col = this.get('columns.' + name); } if (col) { return col; } columns = this.get('columns'); if (isNumber(name) || isArray(name)) { name = toArray(name); cols = columns; for (i = 0, len = name.length - 1; cols && i < len; ++i) { cols = cols[name[i]] && cols[name[i]].children; } return (cols && cols[name[i]]) || null; } return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var record = this.data.getById(seed) || this.data.getByClientId(seed); if (!record) { if (isNumber(seed)) { record = this.data.item(seed); } // TODO: this should be split out to base somehow if (!record && this.view && this.view.getRecord) { record = this.view.getRecord.apply(this.view, arguments); } } return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { var modelList = e.newVal; this.data = e.newVal; if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { var data = this.data.toJSON(); this.data.model = e.newVal; this.data.reset(data); if (!this.get('columns') && data) { if (data.length) { this._initColumns(); } else { this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { var ATTRS, i, len; if (isArray(attrs)) { ATTRS = {}; for (i = 0, len = attrs.length; i < len; ++i) { ATTRS[attrs[i]] = {}; } } else if (isObject(attrs)) { ATTRS = attrs; } return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { var columns = this.get('columns') || [], item; // Default column definition from the configured recordType if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? item = this.data.item(0); if (item.toJSON) { item = item.toJSON(); } this.set('columns', keys(item)); } this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); if (recordType) { modelList.model = recordType; } return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { var recordType; if (!this.data) { recordType = this.get('recordType'); if (data && data.each && data.toJSON) { this.data = data; if (recordType) { this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? this.data = new Y.ModelList(); if (recordType) { this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. if (!columns) { recordType = (config.recordType || config.data === this.data) && this.get('recordType'); if (recordType) { columns = keys(recordType.ATTRS); } else if (isArray(data) && data.length) { columns = keys(data[0]); } if (columns) { this.set('columns', columns); } } this._initColumns(); this._eventHandles = {}; this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { var map = {}; function process(cols) { var i, len, col, key; for (i = 0, len = cols.length; i < len; ++i) { col = cols[i]; key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. if (key && !map[key]) { map[key] = col; } else {Y.log('Key of column matches existing key or name: ' + key, 'warn', NAME);} if (map[col._id]) {Y.log('Key of column matches existing key or name: ' + col._id, 'warn', NAME);} //TODO: named columns can conflict with keyed columns map[col._id] = col; if (col.children) { process(col.children); } } } process(columns); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; function copyObj(o) { var copy = {}, key, val, i; known.push(o); knownCopies.push(copy); for (key in o) { if (o.hasOwnProperty(key)) { val = o[key]; if (isArray(val)) { copy[key] = val.slice(); } else if (isObject(val, true)) { i = arrayIndex(known, val); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { copy[key] = o[key]; } } } return copy; } function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? name = name.replace(/\s+/, '-'); if (keys[name]) { name += (keys[name]++); } else { keys[name] = 1; } return name; } function process(cols, parent) { var columns = [], i, len, col, yuid; for (i = 0, len = cols.length; i < len; ++i) { columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); yuid = Y.stamp(col); // For backward compatibility if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value col.id = yuid; } if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields col.name = col.field; } if (parent) { col._parent = parent; } else { delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. col._id = genId(col.name || col.key || col.id); if (isArray(col.children)) { col.children = process(col.children, col); } } return columns; } return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { this.set('columns', val); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { if (val === null) { val = []; } if (isArray(val)) { this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. val = this.data; } else if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing val = INVALID; } return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { var data; if (val && Y.Recordset && val instanceof Y.Recordset) { data = []; val.each(function (record) { data.push(record.get('data')); }); val = data; } this.set('data', val); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { var modelClass; // Duck type based on known/likely consumed APIs if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { modelClass = val; } else if (isObject(val)) { modelClass = this._createRecordClass(val); } return modelClass || INVALID; } }); /** _This is a documentation entry only_ Columns are described by object literals with a set of properties. There is not an actual `DataTable.Column` class. However, for the purpose of documenting it, this pseudo-class is declared here. DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns) attribute. Each entry in this array is a column definition which may contain any combination of the properties listed below. There are no mandatory properties though a column will usually have a [key](#property_key) property to reference the data it is supposed to show. The [columns](DataTable.html#attr_columns) attribute can accept a plain string in lieu of an object literal, which is the equivalent of an object with the [key](#property_key) property set to that string. @class DataTable.Column */ /** Binds the column values to the named property in the [data](DataTable.html#attr_data). Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter), or [cellTemplate](#property_cellTemplate) is used to populate the content. It should not be set if [children](#property_children) is set. The value is used for the [\_id](#property__id) property unless the [name](#property_name) property is also set. { key: 'username' } The above column definition can be reduced to this: 'username' @property key @type String */ /** An identifier that can be used to locate a column via [getColumn](DataTable.html#method_getColumn) or style columns with class `yui3-datatable-col-NAME` after dropping characters that are not valid for CSS class names. It defaults to the [key](#property_key). The value is used for the [\_id](#property__id) property. { name: 'fullname', formatter: ... } @property name @type String */ /** An alias for [name](#property_name) for backward compatibility. { field: 'fullname', formatter: ... } @property field @type String */ /** Overrides the default unique id assigned `<th id="HERE">`. __Use this with caution__, since it can result in duplicate ids in the DOM. { name: 'checkAll', id: 'check-all', label: ... formatter: ... } @property id @type String */ /** HTML to populate the header `<th>` for the column. It defaults to the value of the [key](#property_key) property or the text `Column n` where _n_ is an ordinal number. { key: 'MfgvaPrtNum', label: 'Part Number' } @property label @@type {HTML} */ /** Used to create stacked headers. Child columns may also contain `children`. There is no limit to the depth of nesting. Columns configured with `children` are for display only and <strong>should not</strong> be configured with a [key](#property_key). Configurations relating to the display of data, such as [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter), [emptyCellValue](#property_emptyCellValue), etc. are ignored. { label: 'Name', children: [ { key: 'firstName', label: 'First`}, { key: 'lastName', label: 'Last`} ]} @property children @type Array */ /** Assigns the value `<th abbr="HERE">`. { key : 'forecast', label: '1yr Target Forecast', abbr : 'Forecast' } @property abbr @type String */ /** Assigns the value `<th title="HERE">`. { key : 'forecast', label: '1yr Target Forecast', title: 'Target Forecast for the Next 12 Months' } @property title @type String */ /** Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE) used by `Y.DataTable.HeaderView` to render the header cell for this column. This is necessary when more control is needed over the markup for the header itself, rather than its content. Use the [label](#property_label) configuration if you don't need to customize the `<th>` iteself. Implementers are strongly encouraged to preserve at least the `{id}` and `{_id}` placeholders in the custom value. { headerTemplate: '<th id="{id}" ' + 'title="Unread" ' + 'class="{className}" ' + '{_id}>&#9679;</th>' } @property headerTemplate @type HTML */ /** Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE) used by `Y.DataTable.BodyView` to render the data cells for this column. This is necessary when more control is needed over the markup for the `<td>` itself, rather than its content. { key: 'id', cellTemplate: '<td class="{className}">' + '<input type="checkbox" ' + 'id="{content}">' + '</td>' } @property cellTemplate @type HTML template */ /** String or function used to translate the raw record data for each cell in a given column into a format better suited to display. If it is a string, it will initially be assumed to be the name of one of the formatting functions in [Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html). If one such formatting function exists, it will be used. If no such named formatter is found, it will be assumed to be a template string and will be expanded. The placeholders can contain the key to any field in the record or the placeholder `{value}` which represents the value of the current field. If the value is a function, it will be assumed to be a formatting function. A formatting function receives a single argument, an object with the following properties: * __value__ The raw value from the record Model to populate this cell. Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`. * __data__ The Model data for this row in simple object format. * __record__ The Model for this row. * __column__ The column configuration object. * __className__ A string of class names to add `<td class="HERE">` in addition to the column class and any classes in the column's className configuration. * __rowIndex__ The index of the current Model in the ModelList. Typically correlates to the row index as well. * __rowClass__ A string of css classes to add `<tr class="HERE"><td....` This is useful to avoid the need for nodeFormatters to add classes to the containing row. The formatter function may return a string value that will be used for the cell contents or it may change the value of the `value`, `className` or `rowClass` properties which well then be used to format the cell. If the value for the cell is returned in the `value` property of the input argument, no value should be returned. { key: 'name', formatter: 'link', // named formatter linkFrom: 'website' // extra column property for link formatter }, { key: 'cost', formatter: '${value}' // formatter template string //formatter: '${cost}' // same result but less portable }, { name: 'Name', // column does not have associated field value // thus, it uses name instead of key formatter: '{firstName} {lastName}' // template references other fields }, { key: 'price', formatter: function (o) { // function both returns a string to show if (o.value > 3) { // and a className to apply to the cell o.className += 'expensive'; } return '$' + o.value.toFixed(2); } }, @property formatter @type String || Function */ /** Used to customize the content of the data cells for this column. `nodeFormatter` is significantly slower than [formatter](#property_formatter) and should be avoided if possible. Unlike [formatter](#property_formatter), `nodeFormatter` has access to the `<td>` element and its ancestors. The function provided is expected to fill in the `<td>` element itself. __Node formatters should return `false`__ except in certain conditions as described in the users guide. The function receives a single object argument with the following properties: * __td__ The `<td>` Node for this cell. * __cell__ If the cell `<td> contains an element with class `yui3-datatable-liner, this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior). * __value__ The raw value from the record Model to populate this cell. Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`. * __data__ The Model data for this row in simple object format. * __record__ The Model for this row. * __column__ The column configuration object. * __rowIndex__ The index of the current Model in the ModelList. _Typically_ correlates to the row index as well. @example nodeFormatter: function (o) { if (o.value < o.data.quota) { o.td.setAttribute('rowspan', 2); o.td.setAttribute('data-term-id', this.record.get('id')); o.td.ancestor().insert( '<tr><td colspan"3">' + '<button class="term">terminate</button>' + '</td></tr>', 'after'); } o.cell.setHTML(o.value); return false; } @property nodeFormatter @type Function */ /** Provides the default value to populate the cell if the data for that cell is `undefined`, `null`, or an empty string. { key: 'price', emptyCellValue: '???' } @property emptyCellValue @type {String|HTML} depending on the setting of allowHTML */ /** Skips the security step of HTML escaping the value for cells in this column. This is also necessary if [emptyCellValue](#property_emptyCellValue) is set with an HTML string. `nodeFormatter`s ignore this configuration. If using a `nodeFormatter`, it is recommended to use [Y.Escape.html()](Escape.html#method_html) on any user supplied content that is to be displayed. { key: 'preview', allowHTML: true } @property allowHTML @type Boolean */ /** A string of CSS classes that will be added to the `<td>`'s `class` attribute. Note, all cells will automatically have a class in the form of "yui3-datatable-col-XXX" added to the `<td>`, where XXX is the column's configured `name`, `key`, or `id` (in that order of preference) sanitized from invalid characters. { key: 'symbol', className: 'no-hide' } @property className @type String */ /** (__read-only__) The unique identifier assigned to each column. This is used for the `id` if not set, and the `_id` if none of [name](#property_name), [field](#property_field), [key](#property_key), or [id](#property_id) are set. @property _yuid @type String @protected */ /** (__read-only__) A unique-to-this-instance name used extensively in the rendering process. It is also used to create the column's classname, as the input name `table.getColumn(HERE)`, and in the column header's `<th data-yui3-col-id="HERE">`. The value is populated by the first of [name](#property_name), [field](#property_field), [key](#property_key), [id](#property_id), or [_yuid](#property__yuid) to have a value. If that value has already been used (such as when multiple columns have the same `key`), an incrementer is added to the end. For example, two columns with `key: "id"` will have `_id`s of "id" and "id2". `table.getColumn("id")` will return the first column, and `table.getColumn("id2")` will return the second. @property _id @type String @protected */ /** (__read-only__) Used by `Y.DataTable.HeaderView` when building stacked column headers. @property _colspan @type Integer @protected */ /** (__read-only__) Used by `Y.DataTable.HeaderView` when building stacked column headers. @property _rowspan @type Integer @protected */ /** (__read-only__) Assigned to all columns in a column's `children` collection. References the parent column object. @property _parent @type DataTable.Column @protected */ /** (__read-only__) Array of the `id`s of the column and all parent columns. Used by `Y.DataTable.BodyView` to populate `<td headers="THIS">` when a cell references more than one header. @property _headers @type Array @protected */ }, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
assets/entry.js
jongha/stock-ai
// require("./style.css"); // document.write(require("./content.js")); import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('root') );
example/dist/app.js
kiqs/chartify
!function(t){function e(e){for(var r,o,i=e[0],a=e[1],c=e[2],u=0,s=[];u<i.length;u++)o=i[u],O[o]&&s.push(O[o][0]),O[o]=0;for(r in a)Object.prototype.hasOwnProperty.call(a,r)&&(t[r]=a[r]);for(L&&L(e);s.length;)s.shift()();return k.push.apply(k,c||[]),n()}function n(){for(var t,e=0;e<k.length;e++){for(var n=k[e],r=!0,o=1;o<n.length;o++){var i=n[o];0!==O[i]&&(r=!1)}r&&(k.splice(e--,1),t=_(_.s=n[0]))}return t}var r=window.webpackHotUpdate;window.webpackHotUpdate=function(t,e){!function(t,e){if(!D[t]||!w[t])return;for(var n in w[t]=!1,e)Object.prototype.hasOwnProperty.call(e,n)&&(g[n]=e[n]);0==--b&&0===m&&j()}(t,e),r&&r(t,e)};var o,i=!0,a="91435a17ab8801798fcf",c=1e4,u={},s=[],f=[];function l(t){var e={_acceptedDependencies:{},_declinedDependencies:{},_selfAccepted:!1,_selfDeclined:!1,_disposeHandlers:[],_main:o!==t,active:!0,accept:function(t,n){if(void 0===t)e._selfAccepted=!0;else if("function"==typeof t)e._selfAccepted=t;else if("object"==typeof t)for(var r=0;r<t.length;r++)e._acceptedDependencies[t[r]]=n||function(){};else e._acceptedDependencies[t]=n||function(){}},decline:function(t){if(void 0===t)e._selfDeclined=!0;else if("object"==typeof t)for(var n=0;n<t.length;n++)e._declinedDependencies[t[n]]=!0;else e._declinedDependencies[t]=!0},dispose:function(t){e._disposeHandlers.push(t)},addDisposeHandler:function(t){e._disposeHandlers.push(t)},removeDisposeHandler:function(t){var n=e._disposeHandlers.indexOf(t);n>=0&&e._disposeHandlers.splice(n,1)},check:M,apply:E,status:function(t){if(!t)return p;d.push(t)},addStatusHandler:function(t){d.push(t)},removeStatusHandler:function(t){var e=d.indexOf(t);e>=0&&d.splice(e,1)},data:u[t]};return o=void 0,e}var d=[],p="idle";function h(t){p=t;for(var e=0;e<d.length;e++)d[e].call(null,t)}var v,g,y,b=0,m=0,x={},w={},D={};function I(t){return+t+""===t?+t:t}function M(t){if("idle"!==p)throw new Error("check() is only allowed in idle status");return i=t,h("check"),(e=c,e=e||1e4,new Promise(function(t,n){if("undefined"==typeof XMLHttpRequest)return n(new Error("No browser support"));try{var r=new XMLHttpRequest,o=_.p+""+a+".hot-update.json";r.open("GET",o,!0),r.timeout=e,r.send(null)}catch(t){return n(t)}r.onreadystatechange=function(){if(4===r.readyState)if(0===r.status)n(new Error("Manifest request to "+o+" timed out."));else if(404===r.status)t();else if(200!==r.status&&304!==r.status)n(new Error("Manifest request to "+o+" failed."));else{try{var e=JSON.parse(r.responseText)}catch(t){return void n(t)}t(e)}}})).then(function(t){if(!t)return h("idle"),null;w={},x={},D=t.c,y=t.h,h("prepare");var e=new Promise(function(t,e){v={resolve:t,reject:e}});for(var n in g={},O)S(n);return"prepare"===p&&0===m&&0===b&&j(),e});var e}function S(t){D[t]?(w[t]=!0,b++,function(t){var e=document.createElement("script");e.charset="utf-8",e.src=_.p+""+t+"."+a+".hot-update.js",document.head.appendChild(e)}(t)):x[t]=!0}function j(){h("ready");var t=v;if(v=null,t)if(i)Promise.resolve().then(function(){return E(i)}).then(function(e){t.resolve(e)},function(e){t.reject(e)});else{var e=[];for(var n in g)Object.prototype.hasOwnProperty.call(g,n)&&e.push(I(n));t.resolve(e)}}function E(e){if("ready"!==p)throw new Error("apply() is only allowed in ready status");var n,r,o,i,c;function f(t){for(var e=[t],n={},r=e.map(function(t){return{chain:[t],id:t}});r.length>0;){var o=r.pop(),a=o.id,c=o.chain;if((i=A[a])&&!i.hot._selfAccepted){if(i.hot._selfDeclined)return{type:"self-declined",chain:c,moduleId:a};if(i.hot._main)return{type:"unaccepted",chain:c,moduleId:a};for(var u=0;u<i.parents.length;u++){var s=i.parents[u],f=A[s];if(f){if(f.hot._declinedDependencies[a])return{type:"declined",chain:c.concat([s]),moduleId:a,parentId:s};-1===e.indexOf(s)&&(f.hot._acceptedDependencies[a]?(n[s]||(n[s]=[]),l(n[s],[a])):(delete n[s],e.push(s),r.push({chain:c.concat([s]),id:s})))}}}}return{type:"accepted",moduleId:t,outdatedModules:e,outdatedDependencies:n}}function l(t,e){for(var n=0;n<e.length;n++){var r=e[n];-1===t.indexOf(r)&&t.push(r)}}e=e||{};var d={},v=[],b={},m=function(){console.warn("[HMR] unexpected require("+w.moduleId+") to disposed module")};for(var x in g)if(Object.prototype.hasOwnProperty.call(g,x)){var w;c=I(x);var M=!1,S=!1,j=!1,E="";switch((w=g[x]?f(c):{type:"disposed",moduleId:x}).chain&&(E="\nUpdate propagation: "+w.chain.join(" -> ")),w.type){case"self-declined":e.onDeclined&&e.onDeclined(w),e.ignoreDeclined||(M=new Error("Aborted because of self decline: "+w.moduleId+E));break;case"declined":e.onDeclined&&e.onDeclined(w),e.ignoreDeclined||(M=new Error("Aborted because of declined dependency: "+w.moduleId+" in "+w.parentId+E));break;case"unaccepted":e.onUnaccepted&&e.onUnaccepted(w),e.ignoreUnaccepted||(M=new Error("Aborted because "+c+" is not accepted"+E));break;case"accepted":e.onAccepted&&e.onAccepted(w),S=!0;break;case"disposed":e.onDisposed&&e.onDisposed(w),j=!0;break;default:throw new Error("Unexception type "+w.type)}if(M)return h("abort"),Promise.reject(M);if(S)for(c in b[c]=g[c],l(v,w.outdatedModules),w.outdatedDependencies)Object.prototype.hasOwnProperty.call(w.outdatedDependencies,c)&&(d[c]||(d[c]=[]),l(d[c],w.outdatedDependencies[c]));j&&(l(v,[w.moduleId]),b[c]=m)}var k,T=[];for(r=0;r<v.length;r++)c=v[r],A[c]&&A[c].hot._selfAccepted&&b[c]!==m&&T.push({module:c,errorHandler:A[c].hot._selfAccepted});h("dispose"),Object.keys(D).forEach(function(t){!1===D[t]&&function(t){delete O[t]}(t)});for(var R,P,L=v.slice();L.length>0;)if(c=L.pop(),i=A[c]){var N={},V=i.hot._disposeHandlers;for(o=0;o<V.length;o++)(n=V[o])(N);for(u[c]=N,i.hot.active=!1,delete A[c],delete d[c],o=0;o<i.children.length;o++){var F=A[i.children[o]];F&&((k=F.parents.indexOf(c))>=0&&F.parents.splice(k,1))}}for(c in d)if(Object.prototype.hasOwnProperty.call(d,c)&&(i=A[c]))for(P=d[c],o=0;o<P.length;o++)R=P[o],(k=i.children.indexOf(R))>=0&&i.children.splice(k,1);for(c in h("apply"),a=y,b)Object.prototype.hasOwnProperty.call(b,c)&&(t[c]=b[c]);var U=null;for(c in d)if(Object.prototype.hasOwnProperty.call(d,c)&&(i=A[c])){P=d[c];var C=[];for(r=0;r<P.length;r++)if(R=P[r],n=i.hot._acceptedDependencies[R]){if(-1!==C.indexOf(n))continue;C.push(n)}for(r=0;r<C.length;r++){n=C[r];try{n(P)}catch(t){e.onErrored&&e.onErrored({type:"accept-errored",moduleId:c,dependencyId:P[r],error:t}),e.ignoreErrored||U||(U=t)}}}for(r=0;r<T.length;r++){var z=T[r];c=z.module,s=[c];try{_(c)}catch(t){if("function"==typeof z.errorHandler)try{z.errorHandler(t)}catch(n){e.onErrored&&e.onErrored({type:"self-accept-error-handler-errored",moduleId:c,error:n,originalError:t}),e.ignoreErrored||U||(U=n),U||(U=t)}else e.onErrored&&e.onErrored({type:"self-accept-errored",moduleId:c,error:t}),e.ignoreErrored||U||(U=t)}}return U?(h("fail"),Promise.reject(U)):(h("idle"),new Promise(function(t){t(v)}))}var A={},O={0:0},k=[];function _(e){if(A[e])return A[e].exports;var n=A[e]={i:e,l:!1,exports:{},hot:l(e),parents:(f=s,s=[],f),children:[]};return t[e].call(n.exports,n,n.exports,function(t){var e=A[t];if(!e)return _;var n=function(n){return e.hot.active?(A[n]?-1===A[n].parents.indexOf(t)&&A[n].parents.push(t):(s=[t],o=n),-1===e.children.indexOf(n)&&e.children.push(n)):(console.warn("[HMR] unexpected require("+n+") from disposed module "+t),s=[]),_(n)},r=function(t){return{configurable:!0,enumerable:!0,get:function(){return _[t]},set:function(e){_[t]=e}}};for(var i in _)Object.prototype.hasOwnProperty.call(_,i)&&"e"!==i&&"t"!==i&&Object.defineProperty(n,i,r(i));return n.e=function(t){return"ready"===p&&h("prepare"),m++,_.e(t).then(e,function(t){throw e(),t});function e(){m--,"prepare"===p&&(x[t]||S(t),0===m&&0===b&&j())}},n.t=function(t,e){return 1&e&&(t=n(t)),_.t(t,-2&e)},n}(e)),n.l=!0,n.exports}_.m=t,_.c=A,_.d=function(t,e,n){_.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},_.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},_.t=function(t,e){if(1&e&&(t=_(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(_.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)_.d(n,r,function(e){return t[e]}.bind(null,r));return n},_.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return _.d(e,"a",e),e},_.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},_.p="https://chartify-213721.firebaseapp.com/",_.h=function(){return a};var T=window.webpackJsonp=window.webpackJsonp||[],R=T.push.bind(T);T.push=e,T=T.slice();for(var P=0;P<T.length;P++)e(T[P]);var L=R;k.push([301,1]),n()}({301:function(t,e,n){n(117),t.exports=n(304)},304:function(t,e,n){"use strict";n.r(e);n(305),n(157);var r=n(2),o=n.n(r),i=n(286),a=n.n(i),c=n(287),u=(n(117),n(67)),s=function(t){a.a.render(o.a.createElement(c.AppContainer,null,o.a.createElement(t,null)),document.getElementById("root"))};s(u.default),t.hot.accept(67,function(t){u=n(67),s(u.default)}.bind(this))},541:function(t,e,n){var r={"./af":159,"./af.js":159,"./ar":160,"./ar-dz":161,"./ar-dz.js":161,"./ar-kw":162,"./ar-kw.js":162,"./ar-ly":163,"./ar-ly.js":163,"./ar-ma":164,"./ar-ma.js":164,"./ar-sa":165,"./ar-sa.js":165,"./ar-tn":166,"./ar-tn.js":166,"./ar.js":160,"./az":167,"./az.js":167,"./be":168,"./be.js":168,"./bg":169,"./bg.js":169,"./bm":170,"./bm.js":170,"./bn":171,"./bn.js":171,"./bo":172,"./bo.js":172,"./br":173,"./br.js":173,"./bs":174,"./bs.js":174,"./ca":175,"./ca.js":175,"./cs":176,"./cs.js":176,"./cv":177,"./cv.js":177,"./cy":178,"./cy.js":178,"./da":179,"./da.js":179,"./de":180,"./de-at":181,"./de-at.js":181,"./de-ch":182,"./de-ch.js":182,"./de.js":180,"./dv":183,"./dv.js":183,"./el":184,"./el.js":184,"./en-SG":185,"./en-SG.js":185,"./en-au":186,"./en-au.js":186,"./en-ca":187,"./en-ca.js":187,"./en-gb":188,"./en-gb.js":188,"./en-ie":189,"./en-ie.js":189,"./en-il":190,"./en-il.js":190,"./en-nz":191,"./en-nz.js":191,"./eo":192,"./eo.js":192,"./es":193,"./es-do":194,"./es-do.js":194,"./es-us":195,"./es-us.js":195,"./es.js":193,"./et":196,"./et.js":196,"./eu":197,"./eu.js":197,"./fa":198,"./fa.js":198,"./fi":199,"./fi.js":199,"./fo":200,"./fo.js":200,"./fr":201,"./fr-ca":202,"./fr-ca.js":202,"./fr-ch":203,"./fr-ch.js":203,"./fr.js":201,"./fy":204,"./fy.js":204,"./ga":205,"./ga.js":205,"./gd":206,"./gd.js":206,"./gl":207,"./gl.js":207,"./gom-latn":208,"./gom-latn.js":208,"./gu":209,"./gu.js":209,"./he":210,"./he.js":210,"./hi":211,"./hi.js":211,"./hr":212,"./hr.js":212,"./hu":213,"./hu.js":213,"./hy-am":214,"./hy-am.js":214,"./id":215,"./id.js":215,"./is":216,"./is.js":216,"./it":217,"./it-ch":218,"./it-ch.js":218,"./it.js":217,"./ja":219,"./ja.js":219,"./jv":220,"./jv.js":220,"./ka":221,"./ka.js":221,"./kk":222,"./kk.js":222,"./km":223,"./km.js":223,"./kn":224,"./kn.js":224,"./ko":225,"./ko.js":225,"./ku":226,"./ku.js":226,"./ky":227,"./ky.js":227,"./lb":228,"./lb.js":228,"./lo":229,"./lo.js":229,"./lt":230,"./lt.js":230,"./lv":231,"./lv.js":231,"./me":232,"./me.js":232,"./mi":233,"./mi.js":233,"./mk":234,"./mk.js":234,"./ml":235,"./ml.js":235,"./mn":236,"./mn.js":236,"./mr":237,"./mr.js":237,"./ms":238,"./ms-my":239,"./ms-my.js":239,"./ms.js":238,"./mt":240,"./mt.js":240,"./my":241,"./my.js":241,"./nb":242,"./nb.js":242,"./ne":243,"./ne.js":243,"./nl":244,"./nl-be":245,"./nl-be.js":245,"./nl.js":244,"./nn":246,"./nn.js":246,"./pa-in":247,"./pa-in.js":247,"./pl":248,"./pl.js":248,"./pt":249,"./pt-br":250,"./pt-br.js":250,"./pt.js":249,"./ro":251,"./ro.js":251,"./ru":252,"./ru.js":252,"./sd":253,"./sd.js":253,"./se":254,"./se.js":254,"./si":255,"./si.js":255,"./sk":256,"./sk.js":256,"./sl":257,"./sl.js":257,"./sq":258,"./sq.js":258,"./sr":259,"./sr-cyrl":260,"./sr-cyrl.js":260,"./sr.js":259,"./ss":261,"./ss.js":261,"./sv":262,"./sv.js":262,"./sw":263,"./sw.js":263,"./ta":264,"./ta.js":264,"./te":265,"./te.js":265,"./tet":266,"./tet.js":266,"./tg":267,"./tg.js":267,"./th":268,"./th.js":268,"./tl-ph":269,"./tl-ph.js":269,"./tlh":270,"./tlh.js":270,"./tr":271,"./tr.js":271,"./tzl":272,"./tzl.js":272,"./tzm":273,"./tzm-latn":274,"./tzm-latn.js":274,"./tzm.js":273,"./ug-cn":275,"./ug-cn.js":275,"./uk":276,"./uk.js":276,"./ur":277,"./ur.js":277,"./uz":278,"./uz-latn":279,"./uz-latn.js":279,"./uz.js":278,"./vi":280,"./vi.js":280,"./x-pseudo":281,"./x-pseudo.js":281,"./yo":282,"./yo.js":282,"./zh-cn":283,"./zh-cn.js":283,"./zh-hk":284,"./zh-hk.js":284,"./zh-tw":285,"./zh-tw.js":285};function o(t){var e=i(t);return n(e)}function i(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}o.keys=function(){return Object.keys(r)},o.resolve=i,t.exports=o,o.id=541},67:function(t,e,n){"use strict";n.r(e);var r={};n.r(r),n.d(r,"updateMoviesDataset",function(){return k}),n.d(r,"getMovies",function(){return T});var o=n(2),i=n.n(o),a=n(288),c=n.n(a),u=n(289),s=n.n(u),f=n(290),l=n.n(f),d=n(291),p=n.n(d),h=n(110),v=n.n(h),g=n(292),y=n.n(g),b=n(86),m=n.n(b),x=n(41),w=n(87),D=n(112),I=n.n(D),M=n(295),S=n.n(M),j=n(1),E=n.n(j);function A(t){var e=[],n=/(\d+)[.](\d+)[.](\d+)/;return t.forEach(function(t){if(t["дата и время"]){var r=n.exec(t["дата и время"]),o=E()(r[0],"DD.MM.YYYY").format("MMM D, YYYY");e.push({xValue:o,yValue:t["моя оценка"],title:"".concat(t["оригинальное название"]||t["русскоязычное название"]," (").concat(t["год"],")")})}}),e.reverse(),e}var O=[{_id:"5aaaca794d870d768ad08f37","русскоязычное название":"Бумажные города","оригинальное название":"Paper Towns","год":2015,"страны":"США","режисcёр":"Джейк Шрейер","жанры":"мелодрама, детектив, комедия","время":109,"моя оценка":7,"рейтинг КиноПоиска":6.128,"число оценок":22402,"рейтинг IMDb":6.4,"число оценок IMDb":65796,"мировая премьера":"18.06.2015","премьера в РФ":"23.07.2015","релиз на DVD":"","бюджет":12e6,"дата и время":"17:43:57 25.07.2015"},{_id:"5aaaca794d870d768ad08f38","русскоязычное название":"Переправа","оригинальное название":"The Crossing","год":2014,"страны":"Китай, США, Гонконг","режисcёр":"Джон Ву","жанры":"драма","время":128,"моя оценка":8,"рейтинг КиноПоиска":6.917,"число оценок":4308,"рейтинг IMDb":6.1,"число оценок IMDb":724,"мировая премьера":"02.12.2014","премьера в РФ":"23.07.2015","релиз на DVD":"16.09.2015","бюджет":65e6,"дата и время":"10:22:02 24.07.2015"},{_id:"5aaaca794d870d768ad08f39","русскоязычное название":"Супер Майк XXL","оригинальное название":"Magic Mike XXL","год":2015,"страны":"США","режисcёр":"Грегори Джейкобс","жанры":"комедия, музыка, драма","время":115,"моя оценка":7,"рейтинг КиноПоиска":6.003,"число оценок":15362,"рейтинг IMDb":5.7,"число оценок IMDb":41380,"мировая премьера":"01.07.2015","премьера в РФ":"02.07.2015","релиз на DVD":"19.11.2015","бюджет":148e5,"дата и время":"23:33:58 08.07.2015"},{_id:"5aaaca794d870d768ad08f3a","русскоязычное название":"Шпион","оригинальное название":"Spy","год":2015,"страны":"США","режисcёр":"Пол Фиг","жанры":"боевик, комедия, криминал","время":119,"моя оценка":7,"рейтинг КиноПоиска":7.116,"число оценок":84055,"рейтинг IMDb":7.1,"число оценок IMDb":182977,"мировая премьера":"20.05.2015","премьера в РФ":"04.06.2015","релиз на DVD":"","бюджет":65e6,"дата и время":"22:06:13 29.06.2015"},{_id:"5aaaca794d870d768ad08f3b","русскоязычное название":"Безумный Макс: Дорога ярости","оригинальное название":"Mad Max: Fury Road","год":2015,"страны":"Австралия, США","режисcёр":"Джордж Миллер","жанры":"боевик, фантастика, приключения","время":120,"моя оценка":5,"рейтинг КиноПоиска":7.817,"число оценок":165522,"рейтинг IMDb":8.1,"число оценок IMDb":607350,"мировая премьера":"07.05.2015","премьера в РФ":"14.05.2015","релиз на DVD":"17.09.2015","бюджет":15e7,"дата и время":"23:47:10 24.05.2015"},{_id:"5aaaca794d870d768ad08f3c","русскоязычное название":"Мстители: Эра Альтрона","оригинальное название":"Avengers: Age of Ultron","год":2015,"страны":"США","режисcёр":"Джосс Уидон","жанры":"фантастика, боевик, приключения","время":141,"моя оценка":7,"рейтинг КиноПоиска":7.293,"число оценок":132250,"рейтинг IMDb":7.5,"число оценок IMDb":477858,"мировая премьера":"13.04.2015","премьера в РФ":"23.04.2015","релиз на DVD":"22.09.2015","бюджет":25e7,"дата и время":"17:19:52 26.04.2015"},{_id:"5aaaca794d870d768ad08f3d","русскоязычное название":"Из машины","оригинальное название":"Ex Machina","год":2014,"страны":"Великобритания","режисcёр":"Алекс Гарленд","жанры":"фантастика, триллер, драма","время":108,"моя оценка":5,"рейтинг КиноПоиска":7.103,"число оценок":66625,"рейтинг IMDb":7.7,"число оценок IMDb":295484,"мировая премьера":"21.01.2015","премьера в РФ":"","релиз на DVD":"28.09.2016","бюджет":15e6,"дата и время":"14:57:11 21.04.2015"},{_id:"5aaaca794d870d768ad08f18","русскоязычное название":"Идеальные незнакомцы","оригинальное название":"Perfetti sconosciuti","год":2016,"страны":"Италия","режисcёр":"Паоло Дженовезе","жанры":"драма, комедия","время":97,"моя оценка":6,"рейтинг КиноПоиска":7.536,"число оценок":9819,"рейтинг IMDb":7.7,"число оценок IMDb":11425,"мировая премьера":"11.02.2016","премьера в РФ":"02.02.2017","релиз на DVD":"","бюджет":null,"дата и время":"18:49:28 28.08.2016"},{_id:"5aaaca794d870d768ad08f19","русскоязычное название":"Джульетта","оригинальное название":"Julieta","год":2016,"страны":"Испания","режисcёр":"Педро Альмодовар","жанры":"драма, мелодрама","время":99,"моя оценка":8,"рейтинг КиноПоиска":6.883,"число оценок":6010,"рейтинг IMDb":7.1,"число оценок IMDb":14254,"мировая премьера":"08.04.2016","премьера в РФ":"04.08.2016","релиз на DVD":"","бюджет":null,"дата и время":"16:04:38 28.08.2016"},{_id:"5aaaca794d870d768ad08f1a","русскоязычное название":"Синг Стрит","оригинальное название":"Sing Street","год":2016,"страны":"Ирландия, Великобритания, США","режисcёр":"Джон Карни","жанры":"драма, мелодрама, комедия","время":106,"моя оценка":10,"рейтинг КиноПоиска":7.641,"число оценок":3408,"рейтинг IMDb":8,"число оценок IMDb":42803,"мировая премьера":"17.03.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"00:27:02 11.08.2016"},{_id:"5aaaca794d870d768ad08f1b","русскоязычное название":"Охотники за привидениями","оригинальное название":"Ghostbusters","год":2016,"страны":"США, Австралия","режисcёр":"Пол Фиг","жанры":"фантастика, фэнтези, боевик","время":116,"моя оценка":6,"рейтинг КиноПоиска":4.377,"число оценок":30928,"рейтинг IMDb":5.4,"число оценок IMDb":111706,"мировая премьера":"09.07.2016","премьера в РФ":"28.07.2016","релиз на DVD":"","бюджет":144e6,"дата и время":"11:42:53 01.08.2016"},{_id:"5aaaca794d870d768ad08f1c","русскоязычное название":"Джейсон Борн","оригинальное название":"Jason Bourne","год":2016,"страны":"Великобритания, Китай, США","режисcёр":"Пол Гринграсс","жанры":"боевик, триллер","время":123,"моя оценка":7,"рейтинг КиноПоиска":6.124,"число оценок":28016,"рейтинг IMDb":6.8,"число оценок IMDb":96857,"мировая премьера":"03.07.2016","премьера в РФ":"01.09.2016","релиз на DVD":"","бюджет":12e7,"дата и время":"21:22:50 30.07.2016"},{_id:"5aaaca794d870d768ad08f1d","русскоязычное название":"Равные","оригинальное название":"Equals","год":2015,"страны":"США","режисcёр":"Дрейк Доримус","жанры":"фантастика, драма, мелодрама","время":101,"моя оценка":5,"рейтинг КиноПоиска":6.051,"число оценок":11355,"рейтинг IMDb":6.1,"число оценок IMDb":13687,"мировая премьера":"11.05.2016","премьера в РФ":"14.07.2016","релиз на DVD":"28.09.2016","бюджет":16e6,"дата и время":"16:15:09 28.07.2016"},{_id:"5aaaca794d870d768ad08f1e","русскоязычное название":"Светская жизнь","оригинальное название":"Cafe Society","год":2016,"страны":"США","режисcёр":"Вуди Аллен","жанры":"драма, мелодрама, комедия","время":96,"моя оценка":6,"рейтинг КиноПоиска":6.945,"число оценок":30519,"рейтинг IMDb":6.7,"число оценок IMDb":40117,"мировая премьера":"11.05.2016","премьера в РФ":"21.07.2016","релиз на DVD":"01.12.2016","бюджет":3e7,"дата и время":"23:17:06 22.07.2016"},{_id:"5aaaca794d870d768ad08f1f","русскоязычное название":"Свадебный угар","оригинальное название":"Mike and Dave Need Wedding Dates","год":2016,"страны":"США","режисcёр":"Джейк Зиманский","жанры":"мелодрама, комедия, приключения","время":98,"моя оценка":6,"рейтинг КиноПоиска":5.631,"число оценок":14701,"рейтинг IMDb":6,"число оценок IMDb":44527,"мировая премьера":"07.07.2016","премьера в РФ":"07.07.2016","релиз на DVD":"","бюджет":33e6,"дата и время":"11:25:42 10.07.2016"},{_id:"5aaaca794d870d768ad08f20","русскоязычное название":"Отмель","оригинальное название":"The Shallows","год":2016,"страны":"США","режисcёр":"Хауме Кольет-Серра","жанры":"ужасы, триллер, драма","время":87,"моя оценка":7,"рейтинг КиноПоиска":6.263,"число оценок":27672,"рейтинг IMDb":6.4,"число оценок IMDb":48404,"мировая премьера":"21.06.2016","премьера в РФ":"07.07.2016","релиз на DVD":"","бюджет":17e6,"дата и время":"22:43:49 08.07.2016"},{_id:"5aaaca794d870d768ad08f21","русскоязычное название":"Славные парни","оригинальное название":"The Nice Guys","год":2016,"страны":"США, Великобритания","режисcёр":"Шейн Блэк","жанры":"криминал, комедия, боевик","время":115,"моя оценка":9,"рейтинг КиноПоиска":7.091,"число оценок":62961,"рейтинг IMDb":7.4,"число оценок IMDb":154127,"мировая премьера":"15.05.2016","премьера в РФ":"16.06.2016","релиз на DVD":"26.09.2016","бюджет":5e7,"дата и время":"09:57:54 23.06.2016"},{_id:"5aaaca794d870d768ad08f22","русскоязычное название":"Иллюзия обмана 2","оригинальное название":"Now You See Me 2","год":2016,"страны":"США, Китай, Великобритания","режисcёр":"Джон М. Чу","жанры":"боевик, триллер, комедия","время":129,"моя оценка":6,"рейтинг КиноПоиска":6.595,"число оценок":78015,"рейтинг IMDb":6.5,"число оценок IMDb":141143,"мировая премьера":"02.06.2016","премьера в РФ":"09.06.2016","релиз на DVD":"28.09.2016","бюджет":9e7,"дата и время":"16:55:47 20.06.2016"},{_id:"5aaaca794d870d768ad08f23","русскоязычное название":"Такой же предатель, как и мы","оригинальное название":"Our Kind of Traitor","год":2016,"страны":"Великобритания, Франция","режисcёр":"Сюзанна Уайт","жанры":"триллер","время":108,"моя оценка":7,"рейтинг КиноПоиска":5.385,"число оценок":2124,"рейтинг IMDb":6.2,"число оценок IMDb":8603,"мировая премьера":"05.05.2016","премьера в РФ":"12.05.2016","релиз на DVD":"","бюджет":null,"дата и время":"13:06:53 26.05.2016"},{_id:"5aaaca794d870d768ad08f24","русскоязычное название":"Выбор","оригинальное название":"The Choice","год":2016,"страны":"США","режисcёр":"Росс Кац","жанры":"драма, мелодрама","время":111,"моя оценка":8,"рейтинг КиноПоиска":6.746,"число оценок":10485,"рейтинг IMDb":6.5,"число оценок IMDb":17202,"мировая премьера":"01.02.2016","премьера в РФ":"21.04.2016","релиз на DVD":"24.10.2016","бюджет":null,"дата и время":"23:19:41 22.04.2016"},{_id:"5aaaca794d870d768ad08f25","русскоязычное название":"Высотка","оригинальное название":"High-Rise","год":2015,"страны":"Великобритания, Бельгия","режисcёр":"Бен Уитли","жанры":"драма","время":119,"моя оценка":1,"рейтинг КиноПоиска":5.581,"число оценок":18382,"рейтинг IMDb":5.7,"число оценок IMDb":20324,"мировая премьера":"26.09.2015","премьера в РФ":"14.04.2016","релиз на DVD":"11.07.2016","бюджет":null,"дата и время":"11:21:42 14.04.2016"},{_id:"5aaaca794d870d768ad08f26","русскоязычное название":"Кловерфилд, 10","оригинальное название":"10 Cloverfield Lane","год":2016,"страны":"США","режисcёр":"Дэн Трахтенберг","жанры":"ужасы, фантастика, триллер","время":104,"моя оценка":7,"рейтинг КиноПоиска":6.816,"число оценок":49562,"рейтинг IMDb":7.3,"число оценок IMDb":155640,"мировая премьера":"08.03.2016","премьера в РФ":"31.03.2016","релиз на DVD":"12.07.2016","бюджет":15e6,"дата и время":"20:11:20 03.04.2016"},{_id:"5aaaca794d870d768ad08f27","русскоязычное название":"Дивергент, глава 3: За стеной","оригинальное название":"Allegiant","год":2016,"страны":"США","режисcёр":"Роберт Швентке","жанры":"фантастика, боевик, триллер","время":121,"моя оценка":6,"рейтинг КиноПоиска":5.53,"число оценок":29560,"рейтинг IMDb":5.7,"число оценок IMDb":56145,"мировая премьера":"08.03.2016","премьера в РФ":"10.03.2016","релиз на DVD":"28.09.2016","бюджет":11e7,"дата и время":"20:35:47 20.03.2016"},{_id:"5aaaca794d870d768ad08f28","русскоязычное название":"Джейн берет ружье","оригинальное название":"Jane Got a Gun","год":2016,"страны":"США","режисcёр":"Гэвин О’Коннор","жанры":"боевик, драма, вестерн","время":98,"моя оценка":6,"рейтинг КиноПоиска":5.653,"число оценок":5540,"рейтинг IMDb":5.8,"число оценок IMDb":10648,"мировая премьера":"01.01.2016","премьера в РФ":"17.03.2016","релиз на DVD":"25.04.2016","бюджет":25e6,"дата и время":"20:35:09 20.03.2016"},{_id:"5aaaca794d870d768ad08f29","русскоязычное название":"Статус: Свободен","оригинальное название":"","год":2015,"страны":"Россия","режисcёр":"Павел Руминов","жанры":"комедия, мелодрама","время":95,"моя оценка":7,"рейтинг КиноПоиска":5.819,"число оценок":19928,"рейтинг IMDb":5.8,"число оценок IMDb":380,"мировая премьера":"21.01.2016","премьера в РФ":"21.01.2016","релиз на DVD":"04.03.2016","бюджет":null,"дата и время":"13:39:00 24.01.2016"},{_id:"5aaaca794d870d768ad08f2a","русскоязычное название":"Рождество","оригинальное название":"The Night Before","год":2015,"страны":"США","режисcёр":"Джонатан Левин","жанры":"комедия","время":101,"моя оценка":5,"рейтинг КиноПоиска":5.916,"число оценок":6015,"рейтинг IMDb":6.5,"число оценок IMDb":39142,"мировая премьера":"20.11.2015","премьера в РФ":"","релиз на DVD":"","бюджет":25e6,"дата и время":"00:41:36 04.01.2016"},{_id:"5aaaca794d870d768ad08f2b","русскоязычное название":"Убийца","оригинальное название":"Sicario","год":2015,"страны":"США","режисcёр":"Дени Вильнёв","жанры":"боевик, триллер, драма","время":121,"моя оценка":7,"рейтинг КиноПоиска":7.036,"число оценок":37605,"рейтинг IMDb":7.6,"число оценок IMDb":213258,"мировая премьера":"14.09.2015","премьера в РФ":"26.11.2015","релиз на DVD":"","бюджет":3e7,"дата и время":"16:32:27 29.11.2015"},{_id:"5aaaca794d870d768ad08f2c","русскоязычное название":"Тайна в их глазах","оригинальное название":"Secret in Their Eyes","год":2015,"страны":"США, Великобритания, Испания","режисcёр":"Билли Рэй","жанры":"триллер, драма, криминал","время":111,"моя оценка":8,"рейтинг КиноПоиска":6.449,"число оценок":10430,"рейтинг IMDb":6.2,"число оценок IMDb":21808,"мировая премьера":"12.11.2015","премьера в РФ":"19.11.2015","релиз на DVD":"","бюджет":195e5,"дата и время":"20:11:43 23.11.2015"},{_id:"5aaaca794d870d768ad08f2d","русскоязычное название":"Голодные игры: Сойка-пересмешница. Часть II","оригинальное название":"The Hunger Games: Mockingjay - Part 2","год":2015,"страны":"США, Германия","режисcёр":"Френсис Лоуренс","жанры":"фантастика, триллер, военный","время":137,"моя оценка":6,"рейтинг КиноПоиска":6.535,"число оценок":63306,"рейтинг IMDb":6.6,"число оценок IMDb":180146,"мировая премьера":"04.11.2015","премьера в РФ":"19.11.2015","релиз на DVD":"","бюджет":16e7,"дата и время":"23:05:54 22.11.2015"},{_id:"5aaaca794d870d768ad08f2e","русскоязычное название":"Стив Джобс","оригинальное название":"Steve Jobs","год":2015,"страны":"Великобритания, США","режисcёр":"Дэнни Бойл","жанры":"драма, биография","время":122,"моя оценка":7,"рейтинг КиноПоиска":6.649,"число оценок":27165,"рейтинг IMDb":7.2,"число оценок IMDb":110041,"мировая премьера":"09.10.2015","премьера в РФ":"01.01.2016","релиз на DVD":"28.09.2016","бюджет":3e7,"дата и время":"17:48:15 15.11.2015"},{_id:"5aaaca794d870d768ad08f2f","русскоязычное название":"007: СПЕКТР","оригинальное название":"Spectre","год":2015,"страны":"Великобритания, США","режисcёр":"Сэм Мендес","жанры":"боевик, триллер, приключения","время":148,"моя оценка":10,"рейтинг КиноПоиска":6.55,"число оценок":68040,"рейтинг IMDb":6.8,"число оценок IMDb":282903,"мировая премьера":"26.10.2015","премьера в РФ":"06.11.2015","релиз на DVD":"","бюджет":245e6,"дата и время":"00:16:44 07.11.2015"},{_id:"5aaaca794d870d768ad08f30","русскоязычное название":"Прогулка","оригинальное название":"The Walk","год":2015,"страны":"США","режисcёр":"Роберт Земекис","жанры":"триллер, драма, приключения","время":123,"моя оценка":9,"рейтинг КиноПоиска":7.331,"число оценок":60767,"рейтинг IMDb":7.4,"число оценок IMDb":87691,"мировая премьера":"30.09.2015","премьера в РФ":"15.10.2015","релиз на DVD":"14.01.2016","бюджет":35e6,"дата и время":"22:35:12 08.10.2015"},{_id:"5aaaca794d870d768ad08f31","русскоязычное название":"Стажёр","оригинальное название":"The Intern","год":2015,"страны":"США","режисcёр":"Нэнси Майерс","жанры":"мелодрама, комедия","время":121,"моя оценка":8,"рейтинг КиноПоиска":7.538,"число оценок":91277,"рейтинг IMDb":7.1,"число оценок IMDb":153584,"мировая премьера":"22.09.2015","премьера в РФ":"24.09.2015","релиз на DVD":"31.12.2015","бюджет":35e6,"дата и время":"21:31:09 27.09.2015"},{_id:"5aaaca794d870d768ad08f32","русскоязычное название":"Эверест","оригинальное название":"Everest","год":2015,"страны":"США, Великобритания, Исландия","режисcёр":"Бальтасар Кормакур","жанры":"триллер, драма, приключения","время":121,"моя оценка":4,"рейтинг КиноПоиска":7.187,"число оценок":76367,"рейтинг IMDb":7.1,"число оценок IMDb":149761,"мировая премьера":"10.09.2015","премьера в РФ":"24.09.2015","релиз на DVD":"28.09.2016","бюджет":55e6,"дата и время":"15:00:19 19.09.2015"},{_id:"5aaaca794d870d768ad08f33","русскоязычное название":"128 ударов сердца в минуту","оригинальное название":"We Are Your Friends","год":2015,"страны":"Великобритания, Франция, США","режисcёр":"Макс Джозеф","жанры":"драма, мелодрама, музыка","время":92,"моя оценка":6,"рейтинг КиноПоиска":6.732,"число оценок":16462,"рейтинг IMDb":6.1,"число оценок IMDb":24257,"мировая премьера":"11.08.2015","премьера в РФ":"03.09.2015","релиз на DVD":"","бюджет":2e6,"дата и время":"23:33:08 30.08.2015"},{_id:"5aaaca794d870d768ad08f34","русскоязычное название":"Агенты А.Н.К.Л.","оригинальное название":"The Man from U.N.C.L.E.","год":2015,"страны":"США, Великобритания","режисcёр":"Гай Ричи","жанры":"боевик, комедия, приключения","время":116,"моя оценка":8,"рейтинг КиноПоиска":7.552,"число оценок":125393,"рейтинг IMDb":7.3,"число оценок IMDb":193278,"мировая премьера":"02.08.2015","премьера в РФ":"13.08.2015","релиз на DVD":"17.12.2015","бюджет":75e6,"дата и время":"18:29:55 16.08.2015"},{_id:"5aaaca794d870d768ad08f35","русскоязычное название":"Миссия невыполнима: Племя изгоев","оригинальное название":"Mission: Impossible - Rogue Nation","год":2015,"страны":"Китай, Гонконг, США","режисcёр":"Кристофер МакКуорри","жанры":"боевик, триллер, приключения","время":131,"моя оценка":7,"рейтинг КиноПоиска":7.076,"число оценок":61287,"рейтинг IMDb":7.4,"число оценок IMDb":247614,"мировая премьера":"23.07.2015","премьера в РФ":"06.08.2015","релиз на DVD":"","бюджет":15e7,"дата и время":"21:31:47 09.08.2015"},{_id:"5aaaca794d870d768ad08f36","русскоязычное название":"Пиксели","оригинальное название":"Pixels","год":2015,"страны":"США, Китай, Канада","режисcёр":"Крис Коламбус","жанры":"мультфильм, фантастика, боевик","время":106,"моя оценка":6,"рейтинг КиноПоиска":5.856,"число оценок":37017,"рейтинг IMDb":5.6,"число оценок IMDb":97622,"мировая премьера":"16.07.2015","премьера в РФ":"23.07.2015","релиз на DVD":"22.10.2015","бюджет":88e6,"дата и время":"17:44:17 25.07.2015"},{_id:"5aaaca794d870d768ad08ee3","русскоязычное название":"Сумерки","оригинальное название":"Twilight","год":1998,"страны":"США","режисcёр":"Роберт Бентон","жанры":"триллер, драма, криминал","время":94,"моя оценка":6,"рейтинг КиноПоиска":6.011,"число оценок":603,"рейтинг IMDb":6.2,"число оценок IMDb":8521,"мировая премьера":"06.03.1998","премьера в РФ":"","релиз на DVD":"","бюджет":28e6,"дата и время":"00:09:44 16.02.2017"},{_id:"5aaaca794d870d768ad08ee4","русскоязычное название":"Мегрэ расставляет сети","оригинальное название":"Maigret Sets a Trap","год":2016,"страны":"Великобритания","режисcёр":"Эшли Пирс","жанры":"триллер, драма, криминал","время":90,"моя оценка":5,"рейтинг КиноПоиска":6.452,"число оценок":1056,"рейтинг IMDb":7,"число оценок IMDb":1741,"мировая премьера":"28.03.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"12:39:59 12.02.2017"},{_id:"5aaaca794d870d768ad08ee5","русскоязычное название":"На пятьдесят оттенков темнее","оригинальное название":"Fifty Shades Darker","год":2017,"страны":"США","режисcёр":"Джеймс Фоули","жанры":"драма, мелодрама","время":118,"моя оценка":7,"рейтинг КиноПоиска":5.287,"число оценок":8248,"рейтинг IMDb":4.9,"число оценок IMDb":15205,"мировая премьера":"07.02.2017","премьера в РФ":"09.02.2017","релиз на DVD":"","бюджет":55e6,"дата и время":"15:39:52 10.02.2017"},{_id:"5aaaca794d870d768ad08ee6","русскоязычное название":"Нерв","оригинальное название":"Nerve","год":2016,"страны":"США, Гонконг","режисcёр":"Генри Джуст, Эриель Шульман","жанры":"триллер, криминал, приключения","время":96,"моя оценка":8,"рейтинг КиноПоиска":6.556,"число оценок":31014,"рейтинг IMDb":6.7,"число оценок IMDb":46086,"мировая премьера":"12.07.2016","премьера в РФ":"15.09.2016","релиз на DVD":"","бюджет":2e7,"дата и время":"00:27:34 04.02.2017"},{_id:"5aaaca794d870d768ad08ee7","русскоязычное название":"Найди меня, если сможешь","оригинальное название":"Come and Find Me","год":2016,"страны":"Великобритания","режисcёр":"Зак Уэдон","жанры":"триллер, драма","время":112,"моя оценка":10,"рейтинг КиноПоиска":5.437,"число оценок":933,"рейтинг IMDb":5.7,"число оценок IMDb":2810,"мировая премьера":"11.11.2016","премьера в РФ":"22.12.2016","релиз на DVD":"","бюджет":null,"дата и время":"22:38:15 25.01.2017"},{_id:"5aaaca794d870d768ad08ee8","русскоязычное название":"Топ-модель","оригинальное название":"The Model","год":2016,"страны":"Дания","режисcёр":"Мадс Маттисен","жанры":"мелодрама","время":105,"моя оценка":5,"рейтинг КиноПоиска":5.705,"число оценок":3708,"рейтинг IMDb":5.8,"число оценок IMDb":1408,"мировая премьера":"11.02.2016","премьера в РФ":"05.05.2016","релиз на DVD":"","бюджет":null,"дата и время":"00:35:15 25.01.2017"},{_id:"5aaaca794d870d768ad08ee9","русскоязычное название":"Почему он?","оригинальное название":"Why Him?","год":2016,"страны":"США","режисcёр":"Джон Гамбург","жанры":"комедия","время":111,"моя оценка":6,"рейтинг КиноПоиска":6.769,"число оценок":13616,"рейтинг IMDb":6.6,"число оценок IMDb":13561,"мировая премьера":"17.12.2016","премьера в РФ":"12.01.2017","релиз на DVD":"","бюджет":38e6,"дата и время":"19:25:17 20.01.2017"},{_id:"5aaaca794d870d768ad08eea","русскоязычное название":"Бункер","оригинальное название":"La cara oculta","год":2011,"страны":"Колумбия, Испания","режисcёр":"Андрес Байс","жанры":"триллер, драма, детектив","время":92,"моя оценка":9,"рейтинг КиноПоиска":7.267,"число оценок":27883,"рейтинг IMDb":7.4,"число оценок IMDb":20459,"мировая премьера":"16.09.2011","премьера в РФ":"08.11.2012","релиз на DVD":"17.01.2013","бюджет":26e5,"дата и время":"18:49:16 15.01.2017"},{_id:"5aaaca794d870d768ad08eeb","русскоязычное название":"Перевозчик: Наследие","оригинальное название":"The Transporter Refueled","год":2015,"страны":"Франция, Китай, Бельгия","режисcёр":"Камиль Деламарр","жанры":"боевик, триллер, криминал","время":96,"моя оценка":4,"рейтинг КиноПоиска":5.079,"число оценок":11527,"рейтинг IMDb":5.1,"число оценок IMDb":29722,"мировая премьера":"25.08.2015","премьера в РФ":"10.09.2015","релиз на DVD":"","бюджет":25e6,"дата и время":"18:49:00 15.01.2017"},{_id:"5aaaca794d870d768ad08eec","русскоязычное название":"Ворошиловский стрелок","оригинальное название":"","год":1999,"страны":"Россия","режисcёр":"Станислав Говорухин","жанры":"драма, криминал","время":95,"моя оценка":9,"рейтинг КиноПоиска":7.807,"число оценок":56197,"рейтинг IMDb":7.5,"число оценок IMDb":1995,"мировая премьера":"15.03.2001","премьера в РФ":"21.04.1999","релиз на DVD":"14.04.2011","бюджет":null,"дата и время":"16:15:01 14.01.2017"},{_id:"5aaaca794d870d768ad08eed","русскоязычное название":"Закон ночи","оригинальное название":"Live by Night","год":2016,"страны":"США","режисcёр":"Бен Аффлек","жанры":"драма, криминал","время":129,"моя оценка":8,"рейтинг КиноПоиска":6.598,"число оценок":6996,"рейтинг IMDb":6.5,"число оценок IMDb":12474,"мировая премьера":"20.01.2016","премьера в РФ":"12.01.2017","релиз на DVD":"","бюджет":65e6,"дата и время":"12:53:22 13.01.2017"},{_id:"5aaaca794d870d768ad08eee","русскоязычное название":"Пятеро","оригинальное название":"Five","год":2016,"страны":"Франция","режисcёр":"Игорь Готсман","жанры":"комедия","время":102,"моя оценка":6,"рейтинг КиноПоиска":5.744,"число оценок":254,"рейтинг IMDb":6.4,"число оценок IMDb":881,"мировая премьера":"30.03.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"00:29:17 10.01.2017"},{_id:"5aaaca794d870d768ad08eef","русскоязычное название":"Быстрая, как ветер","оригинальное название":"Veloce come il vento","год":2016,"страны":"Италия","режисcёр":"Маттео Ровере","жанры":"драма, спорт","время":118,"моя оценка":9,"рейтинг КиноПоиска":7.214,"число оценок":286,"рейтинг IMDb":7.5,"число оценок IMDb":1726,"мировая премьера":"07.04.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"22:29:20 09.01.2017"},{_id:"5aaaca794d870d768ad08ef0","русскоязычное название":"Под покровом ночи","оригинальное название":"Nocturnal Animals","год":2016,"страны":"США","режисcёр":"Том Форд","жанры":"триллер, драма","время":116,"моя оценка":4,"рейтинг КиноПоиска":7.355,"число оценок":25738,"рейтинг IMDb":7.6,"число оценок IMDb":69652,"мировая премьера":"04.11.2016","премьера в РФ":"08.12.2016","релиз на DVD":"","бюджет":225e5,"дата и время":"01:28:16 09.01.2017"},{_id:"5aaaca794d870d768ad08ef1","русскоязычное название":"Кредо убийцы","оригинальное название":"Assassin's Creed","год":2016,"страны":"Великобритания, Франция, Гонконг","режисcёр":"Джастин Курзель","жанры":"фантастика, фэнтези, боевик","время":115,"моя оценка":6,"рейтинг КиноПоиска":6.142,"число оценок":35196,"рейтинг IMDb":6.4,"число оценок IMDb":52694,"мировая премьера":"14.12.2016","премьера в РФ":"05.01.2017","релиз на DVD":"","бюджет":125e6,"дата и время":"22:32:07 08.01.2017"},{_id:"5aaaca794d870d768ad08ef2","русскоязычное название":"Зажигание","оригинальное название":"Combustion","год":2013,"страны":"Испания","режисcёр":"Даниэль Кальпарсоро","жанры":"мелодрама, приключения, боевик","время":104,"моя оценка":9,"рейтинг КиноПоиска":6.632,"число оценок":9058,"рейтинг IMDb":5.8,"число оценок IMDb":2565,"мировая премьера":"26.04.2013","премьера в РФ":"25.07.2013","релиз на DVD":"04.09.2013","бюджет":null,"дата и время":"23:12:29 06.01.2017"},{_id:"5aaaca794d870d768ad08ef3","русскоязычное название":"Новогодний корпоратив","оригинальное название":"Office Christmas Party","год":2016,"страны":"США","режисcёр":"Джош Гордон, Уилл Спек","жанры":"комедия","время":105,"моя оценка":7,"рейтинг КиноПоиска":5.836,"число оценок":5409,"рейтинг IMDb":6,"число оценок IMDb":11488,"мировая премьера":"07.12.2016","премьера в РФ":"08.12.2016","релиз на DVD":"","бюджет":45e6,"дата и время":"22:18:06 02.01.2017"},{_id:"5aaaca794d870d768ad08ef4","русскоязычное название":"Пассажиры","оригинальное название":"Passengers","год":2016,"страны":"США","режисcёр":"Мортен Тильдум","жанры":"фантастика, драма, мелодрама","время":116,"моя оценка":10,"рейтинг КиноПоиска":7.12,"число оценок":52649,"рейтинг IMDb":7,"число оценок IMDb":88086,"мировая премьера":"14.12.2016","премьера в РФ":"22.12.2016","релиз на DVD":"","бюджет":11e7,"дата и время":"15:33:01 28.12.2016"},{_id:"5aaaca794d870d768ad08ef5","русскоязычное название":"Хороший мальчик","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Оксана Карас","жанры":"комедия","время":95,"моя оценка":9,"рейтинг КиноПоиска":6.531,"число оценок":10221,"рейтинг IMDb":null,"число оценок IMDb":null,"мировая премьера":"18.11.2016","премьера в РФ":"10.11.2016","релиз на DVD":"22.12.2016","бюджет":null,"дата и время":"03:26:59 24.12.2016"},{_id:"5aaaca794d870d768ad08ef6","русскоязычное название":"Дневной свет","оригинальное название":"Daglicht","год":2013,"страны":"Нидерланды","режисcёр":"Дидерик Ван Ружен","жанры":"триллер, драма, детектив","время":114,"моя оценка":7,"рейтинг КиноПоиска":6.86,"число оценок":974,"рейтинг IMDb":7,"число оценок IMDb":2647,"мировая премьера":"11.04.2013","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"21:04:01 18.12.2016"},{_id:"5aaaca794d870d768ad08ef7","русскоязычное название":"Оцепенелый","оригинальное название":"Numb","год":2015,"страны":"Канада","режисcёр":"Джейсон Р. Гуд","жанры":"триллер, детектив","время":90,"моя оценка":4,"рейтинг КиноПоиска":5.572,"число оценок":178,"рейтинг IMDb":6,"число оценок IMDb":454,"мировая премьера":"02.03.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"12:07:16 18.12.2016"},{_id:"5aaaca794d870d768ad08ef8","русскоязычное название":"Седьмой этаж","оригинальное название":"Septimo","год":2013,"страны":"Испания, Аргентина","режисcёр":"Пачи Амескуа","жанры":"триллер, детектив","время":88,"моя оценка":7,"рейтинг КиноПоиска":5.646,"число оценок":327,"рейтинг IMDb":5.8,"число оценок IMDb":3348,"мировая премьера":"05.09.2013","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"22:35:14 17.12.2016"},{_id:"5aaaca794d870d768ad08ef9","русскоязычное название":"Тело","оригинальное название":"El cuerpo","год":2012,"страны":"Испания","режисcёр":"Ориол Паоло","жанры":"триллер, детектив","время":108,"моя оценка":9,"рейтинг КиноПоиска":7.415,"число оценок":9795,"рейтинг IMDb":7.5,"число оценок IMDb":17609,"мировая премьера":"21.12.2012","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"20:13:52 11.12.2016"},{_id:"5aaaca794d870d768ad08efa","русскоязычное название":"Спящие","оригинальное название":"Sleepers","год":1996,"страны":"США","режисcёр":"Барри Левинсон","жанры":"триллер, драма, криминал","время":147,"моя оценка":9,"рейтинг КиноПоиска":7.863,"число оценок":23924,"рейтинг IMDb":7.6,"число оценок IMDb":158322,"мировая премьера":"18.10.1996","премьера в РФ":"","релиз на DVD":"","бюджет":44e6,"дата и время":"18:14:58 11.12.2016"},{_id:"5aaaca794d870d768ad08efb","русскоязычное название":"Честная игра","оригинальное название":"Fair Game","год":1995,"страны":"США","режисcёр":"Эндрю Сайпс","жанры":"боевик, триллер, криминал","время":91,"моя оценка":7,"рейтинг КиноПоиска":5.938,"число оценок":1097,"рейтинг IMDb":4.1,"число оценок IMDb":10368,"мировая премьера":"03.11.1995","премьера в РФ":"","релиз на DVD":"01.11.2001","бюджет":5e7,"дата и время":"01:01:09 11.12.2016"},{_id:"5aaaca794d870d768ad08efc","русскоязычное название":"Мисс Конгениальность 2: Прекрасна и опасна","оригинальное название":"Miss Congeniality 2: Armed & Fabulous","год":2005,"страны":"США","режисcёр":"Джон Пасквин","жанры":"боевик, комедия, криминал","время":115,"моя оценка":8,"рейтинг КиноПоиска":6.124,"число оценок":16008,"рейтинг IMDb":5,"число оценок IMDb":50361,"мировая премьера":"23.03.2005","премьера в РФ":"14.04.2005","релиз на DVD":"16.06.2011","бюджет":45e6,"дата и время":"22:44:05 10.12.2016"},{_id:"5aaaca794d870d768ad08efd","русскоязычное название":"Мисс Конгениальность","оригинальное название":"Miss Congeniality","год":2e3,"страны":"США","режисcёр":"Дональд Питри","жанры":"боевик, комедия, криминал","время":110,"моя оценка":8,"рейтинг КиноПоиска":7.097,"число оценок":41422,"рейтинг IMDb":6.2,"число оценок IMDb":139405,"мировая премьера":"14.12.2000","премьера в РФ":"12.07.2001","релиз на DVD":"01.11.2001","бюджет":45e6,"дата и время":"22:43:44 10.12.2016"},{_id:"5aaaca794d870d768ad08efe","русскоязычное название":"Холодный фронт","оригинальное название":"","год":2015,"страны":"Россия, Франция","режисcёр":"Роман Волобуев","жанры":"триллер, мелодрама","время":91,"моя оценка":8,"рейтинг КиноПоиска":5.458,"число оценок":2585,"рейтинг IMDb":5.4,"число оценок IMDb":185,"мировая премьера":"","премьера в РФ":"14.01.2016","релиз на DVD":"01.02.2016","бюджет":null,"дата и время":"22:30:38 07.12.2016"},{_id:"5aaaca794d870d768ad08eff","русскоязычное название":"Союзники","оригинальное название":"Allied","год":2016,"страны":"США, Великобритания","режисcёр":"Роберт Земекис","жанры":"боевик, триллер, драма","время":121,"моя оценка":10,"рейтинг КиноПоиска":7.175,"число оценок":17546,"рейтинг IMDb":7.1,"число оценок IMDb":35119,"мировая премьера":"13.11.2016","премьера в РФ":"01.12.2016","релиз на DVD":"","бюджет":85e6,"дата и время":"12:36:59 02.12.2016"},{_id:"5aaaca794d870d768ad08f00","русскоязычное название":"Стальная бабочка","оригинальное название":"","год":2012,"страны":"Россия","режисcёр":"Ренат Давлетьяров","жанры":"драма, криминал, детектив","время":107,"моя оценка":7,"рейтинг КиноПоиска":7.012,"число оценок":12704,"рейтинг IMDb":7.3,"число оценок IMDb":905,"мировая премьера":"","премьера в РФ":"01.11.2012","релиз на DVD":"26.11.2012","бюджет":null,"дата и время":"17:01:48 30.11.2016"},{_id:"5aaaca794d870d768ad08f01","русскоязычное название":"Училка","оригинальное название":"","год":2015,"страны":"Россия","режисcёр":"Алексей Петрухин","жанры":"драма, боевик, криминал","время":134,"моя оценка":5,"рейтинг КиноПоиска":5.749,"число оценок":5137,"рейтинг IMDb":5.9,"число оценок IMDb":170,"мировая премьера":"11.12.2015","премьера в РФ":"26.11.2015","релиз на DVD":"24.10.2016","бюджет":null,"дата и время":"00:37:26 28.11.2016"},{_id:"5aaaca794d870d768ad08f02","русскоязычное название":"Дурак","оригинальное название":"","год":2014,"страны":"Россия","режисcёр":"Юрий Быков","жанры":"драма","время":116,"моя оценка":9,"рейтинг КиноПоиска":8,"число оценок":78398,"рейтинг IMDb":8,"число оценок IMDb":4568,"мировая премьера":"09.11.2014","премьера в РФ":"11.12.2014","релиз на DVD":"22.01.2015","бюджет":13e5,"дата и время":"20:55:35 27.11.2016"},{_id:"5aaaca794d870d768ad08f03","русскоязычное название":"Ледокол","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Николай Хомерики","жанры":"драма","время":120,"моя оценка":7,"рейтинг КиноПоиска":6.512,"число оценок":16384,"рейтинг IMDb":null,"число оценок IMDb":null,"мировая премьера":"04.11.2016","премьера в РФ":"20.10.2016","релиз на DVD":"12.12.2016","бюджет":1e7,"дата и время":"00:33:11 23.11.2016"},{_id:"5aaaca794d870d768ad08f04","русскоязычное название":"Фантастические твари и где они обитают","оригинальное название":"Fantastic Beasts and Where to Find Them","год":2016,"страны":"Великобритания, США","режисcёр":"Дэвид Йейтс","жанры":"фэнтези, приключения, семейный","время":133,"моя оценка":8,"рейтинг КиноПоиска":7.632,"число оценок":84065,"рейтинг IMDb":7.6,"число оценок IMDb":159559,"мировая премьера":"08.11.2016","премьера в РФ":"17.11.2016","релиз на DVD":"","бюджет":18e7,"дата и время":"20:00:45 20.11.2016"},{_id:"5aaaca794d870d768ad08f05","русскоязычное название":"Сноуден","оригинальное название":"Snowden","год":2016,"страны":"Франция, Германия, США","режисcёр":"Оливер Стоун","жанры":"триллер, драма, биография","время":134,"моя оценка":7,"рейтинг КиноПоиска":6.922,"число оценок":20549,"рейтинг IMDb":7.3,"число оценок IMDb":62982,"мировая премьера":"21.07.2016","премьера в РФ":"15.09.2016","релиз на DVD":"","бюджет":4e7,"дата и время":"00:30:52 20.11.2016"},{_id:"5aaaca794d870d768ad08f06","русскоязычное название":"Паранойя","оригинальное название":"Disturbia","год":2007,"страны":"США","режисcёр":"Ди Джей Карузо","жанры":"триллер, драма, детектив","время":104,"моя оценка":8,"рейтинг КиноПоиска":7.524,"число оценок":50131,"рейтинг IMDb":6.9,"число оценок IMDb":179463,"мировая премьера":"04.04.2007","премьера в РФ":"26.04.2007","релиз на DVD":"15.03.2012","бюджет":2e7,"дата и время":"12:43:10 14.11.2016"},{_id:"5aaaca794d870d768ad08f07","русскоязычное название":"Прибытие","оригинальное название":"Arrival","год":2016,"страны":"США","режисcёр":"Дени Вильнёв","жанры":"фантастика, триллер, драма","время":116,"моя оценка":5,"рейтинг КиноПоиска":7.586,"число оценок":70178,"рейтинг IMDb":8.1,"число оценок IMDb":222863,"мировая премьера":"22.09.2016","премьера в РФ":"11.11.2016","релиз на DVD":"","бюджет":47e6,"дата и время":"19:16:47 12.11.2016"},{_id:"5aaaca794d870d768ad08f08","русскоязычное название":"Коллектор","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Алексей Красовский","жанры":"драма, триллер","время":74,"моя оценка":7,"рейтинг КиноПоиска":6.91,"число оценок":23563,"рейтинг IMDb":6.9,"число оценок IMDb":959,"мировая премьера":"06.10.2016","премьера в РФ":"06.10.2016","релиз на DVD":"14.11.2016","бюджет":null,"дата и время":"22:52:17 11.11.2016"},{_id:"5aaaca794d870d768ad08f09","русскоязычное название":"Расплата","оригинальное название":"The Accountant","год":2016,"страны":"США","режисcёр":"Гэвин О’Коннор","жанры":"боевик, триллер, драма","время":128,"моя оценка":9,"рейтинг КиноПоиска":7.414,"число оценок":44365,"рейтинг IMDb":7.4,"число оценок IMDb":125963,"мировая премьера":"13.10.2016","премьера в РФ":"27.10.2016","релиз на DVD":"","бюджет":44e6,"дата и время":"12:20:23 01.11.2016"},{_id:"5aaaca794d870d768ad08f0a","русскоязычное название":"Завтрак у папы","оригинальное название":"","год":2015,"страны":"Россия","режисcёр":"Мария Кравченко","жанры":"комедия","время":96,"моя оценка":7,"рейтинг КиноПоиска":6.154,"число оценок":4938,"рейтинг IMDb":6.1,"число оценок IMDb":127,"мировая премьера":"24.06.2016","премьера в РФ":"23.06.2016","релиз на DVD":"25.07.2016","бюджет":null,"дата и время":"22:05:56 21.10.2016"},{_id:"5aaaca794d870d768ad08f0b","русскоязычное название":"Скотт Пилигрим против всех","оригинальное название":"Scott Pilgrim vs. the World","год":2010,"страны":"США, Великобритания, Канада","режисcёр":"Эдгар Райт","жанры":"фэнтези, боевик, мелодрама","время":112,"моя оценка":6,"рейтинг КиноПоиска":7.207,"число оценок":96526,"рейтинг IMDb":7.5,"число оценок IMDb":285645,"мировая премьера":"11.08.2010","премьера в РФ":"19.08.2010","релиз на DVD":"25.01.2011","бюджет":6e7,"дата и время":"23:13:40 17.10.2016"},{_id:"5aaaca794d870d768ad08f0c","русскоязычное название":"Большой всплеск","оригинальное название":"A Bigger Splash","год":2015,"страны":"Италия, Франция","режисcёр":"Лука Гуаданьино","жанры":"триллер, криминал, детектив","время":125,"моя оценка":7,"рейтинг КиноПоиска":6.177,"число оценок":5806,"рейтинг IMDb":6.4,"число оценок IMDb":10701,"мировая премьера":"26.11.2015","премьера в РФ":"09.06.2016","релиз на DVD":"11.07.2016","бюджет":null,"дата и время":"12:47:00 11.10.2016"},{_id:"5aaaca794d870d768ad08f0d","русскоязычное название":"Девушка в поезде","оригинальное название":"The Girl on the Train","год":2016,"страны":"США","режисcёр":"Тейт Тейлор","жанры":"триллер, драма, детектив","время":112,"моя оценка":7,"рейтинг КиноПоиска":6.555,"число оценок":37333,"рейтинг IMDb":6.6,"число оценок IMDb":73908,"мировая премьера":"20.09.2016","премьера в РФ":"03.11.2016","релиз на DVD":"","бюджет":45e6,"дата и время":"23:30:32 08.10.2016"},{_id:"5aaaca794d870d768ad08f0e","русскоязычное название":"Смертельное оружие","оригинальное название":"Lethal Weapon","год":2016,"страны":"США","режисcёр":"Стив Бойум, Джейсон Энслер, МакДжи","жанры":"боевик, триллер, драма","время":60,"моя оценка":7,"рейтинг КиноПоиска":7.285,"число оценок":1433,"рейтинг IMDb":7.9,"число оценок IMDb":12475,"мировая премьера":"21.09.2016","премьера в РФ":"","релиз на DVD":"","бюджет":null,"дата и время":"23:30:11 08.10.2016"},{_id:"5aaaca794d870d768ad08f0f","русскоязычное название":"Она","оригинальное название":"Elle","год":2016,"страны":"Франция, Германия, Бельгия","режисcёр":"Пол Верховен","жанры":"триллер, драма","время":130,"моя оценка":7,"рейтинг КиноПоиска":6.63,"число оценок":11926,"рейтинг IMDb":7.3,"число оценок IMDb":22215,"мировая премьера":"25.05.2016","премьера в РФ":"22.09.2016","релиз на DVD":"","бюджет":null,"дата и время":"10:53:13 05.10.2016"},{_id:"5aaaca794d870d768ad08f10","русскоязычное название":"Бедная Саша","оригинальное название":"","год":1997,"страны":"Россия","режисcёр":"Тигран Кеосаян","жанры":"комедия, приключения, семейный","время":95,"моя оценка":8,"рейтинг КиноПоиска":7.621,"число оценок":11355,"рейтинг IMDb":7.1,"число оценок IMDb":330,"мировая премьера":"","премьера в РФ":"26.12.1997","релиз на DVD":"","бюджет":null,"дата и время":"15:40:51 01.10.2016"},{_id:"5aaaca794d870d768ad08f11","русскоязычное название":"Саранча","оригинальное название":"","год":2013,"страны":"Россия","режисcёр":"Егор Баранов","жанры":"триллер","время":118,"моя оценка":9,"рейтинг КиноПоиска":6.475,"число оценок":10478,"рейтинг IMDb":5.6,"число оценок IMDb":165,"мировая премьера":"03.05.2016","премьера в РФ":"05.11.2015","релиз на DVD":"14.01.2016","бюджет":null,"дата и время":"15:35:10 01.10.2016"},{_id:"5aaaca794d870d768ad08f12","русскоязычное название":"Вакантна жизнь шеф-повара","оригинальное название":"","год":2015,"страны":"Россия","режисcёр":"Рустам Ильясов","жанры":"триллер, драма, фантастика","время":86,"моя оценка":7,"рейтинг КиноПоиска":6.38,"число оценок":2095,"рейтинг IMDb":null,"число оценок IMDb":null,"мировая премьера":"","премьера в РФ":"10.03.2016","релиз на DVD":"","бюджет":15e5,"дата и время":"15:35:04 01.10.2016"},{_id:"5aaaca794d870d768ad08f13","русскоязычное название":"Чистое искусство","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Ренат Давлетьяров","жанры":"триллер, детектив","время":93,"моя оценка":8,"рейтинг КиноПоиска":6.051,"число оценок":3884,"рейтинг IMDb":6.3,"число оценок IMDb":40,"мировая премьера":"","премьера в РФ":"09.06.2016","релиз на DVD":"","бюджет":null,"дата и время":"15:34:53 01.10.2016"},{_id:"5aaaca794d870d768ad08f14","русскоязычное название":"Дуэлянт","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Алексей Мизгирёв","жанры":"драма","время":110,"моя оценка":8,"рейтинг КиноПоиска":6.64,"число оценок":30373,"рейтинг IMDb":6.5,"число оценок IMDb":942,"мировая премьера":"29.09.2016","премьера в РФ":"29.09.2016","релиз на DVD":"","бюджет":null,"дата и время":"15:34:28 01.10.2016"},{_id:"5aaaca794d870d768ad08f15","русскоязычное название":"В августе 44-го","оригинальное название":"","год":2001,"страны":"Россия, Беларусь","режисcёр":"Михаил Пташук","жанры":"боевик, триллер, драма","время":118,"моя оценка":8,"рейтинг КиноПоиска":7.884,"число оценок":23570,"рейтинг IMDb":7.6,"число оценок IMDb":786,"мировая премьера":"","премьера в РФ":"","релиз на DVD":"10.04.2012","бюджет":5052780,"дата и время":"23:30:29 24.09.2016"},{_id:"5aaaca794d870d768ad08f16","русскоязычное название":"Экипаж","оригинальное название":"","год":2016,"страны":"Россия","режисcёр":"Николай Лебедев","жанры":"драма, приключения, триллер","время":138,"моя оценка":9,"рейтинг КиноПоиска":7.779,"число оценок":63666,"рейтинг IMDb":7,"число оценок IMDb":2025,"мировая премьера":"22.04.2016","премьера в РФ":"21.04.2016","релиз на DVD":"28.09.2016","бюджет":null,"дата и время":"21:53:41 16.09.2016"},{_id:"5aaaca794d870d768ad08f17","русскоязычное название":"Чудо на Гудзоне","оригинальное название":"Sully","год":2016,"страны":"США","режисcёр":"Клинт Иствуд","жанры":"драма, биография","время":96,"моя оценка":7,"рейтинг КиноПоиска":7.43,"число оценок":39750,"рейтинг IMDb":7.6,"число оценок IMDb":71964,"мировая премьера":"06.09.2016","премьера в РФ":"08.09.2016","релиз на DVD":"","бюджет":6e7,"дата и время":"18:05:10 11.09.2016"}];function k(t){return{type:"UPDATE_MOVIES_DATASET",movies:t}}function _(){return(_=S()(I.a.mark(function t(){return I.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",A(O));case 1:case"end":return t.stop()}},t)}))).apply(this,arguments)}function T(){return function(t){(function(){return _.apply(this,arguments)})().then(function(e){return t(k(e))})}}var R=n(68),P=n.n(R),L=function(t){var e=t.data,n=t.metadata;return i.a.createElement(i.a.Fragment,null,i.a.createElement(P.a,{data:e,container:n.container,config:{theme:"blue",width:50,height:10,isLineChart:!1,bordered:!1}}),i.a.createElement(P.a,{data:e,container:n.container,config:{theme:"white",width:50,height:10,isLineChart:!1,bordered:!1}}),i.a.createElement(P.a,{data:e,container:n.container,config:{theme:"default",width:50,height:10,isLineChart:!1,bordered:!1}}),i.a.createElement(P.a,{data:e,container:n.container,config:{theme:"default",width:50,height:10,isLineChart:!0,bordered:!1}}))},N=function(t){function e(){var t,n;c()(this,e);for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];return n=l()(this,(t=p()(e)).call.apply(t,[this].concat(o))),m()(v()(n),"state",{moviesMetadata:{container:"films-container",chart:"films"}}),n}return y()(e,t),s()(e,[{key:"componentWillMount",value:function(){this.props.actions.getMovies()}},{key:"render",value:function(){var t=this.props.movies,e=this.state.moviesMetadata;return i.a.createElement(L,{data:t,metadata:e})}}]),e}(o.Component),V=Object(w.b)(function(t){return{movies:t.movies}},function(t){return{actions:Object(x.b)(r,t)}})(N),F=n(296),U=n.n(F);function C(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function z(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?C(n,!0).forEach(function(e){m()(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):C(n).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}var B={movies:[],albums:[]};var q=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:B,e=arguments.length>1?arguments[1]:void 0;switch(e.type){case"UPDATE_MOVIES_DATASET":return z({},t,{movies:e.movies});case"UPDATE_ALBUMS_DATASET":return z({},t,{albums:e.albums});default:return t}},G=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||x.c,W=Object(x.d)(q,G(Object(x.a)(U.a))),Y=n(113),H=Y.a.div.withConfig({displayName:"styles__Root",componentId:"sc-41lvd1-0"})(["margin:0 auto;width:1200px;max-width:1200px;.container{width:1000px;margin:0px auto;}header{padding:20px 0 0 0;.project-title{margin:0 auto;width:650px;text-align:center;font-size:1.5em;text-align:center;color:palevioletred;.main-header{font-size:36px;margin:0;}.sub-header{font-size:16px;color:#3092e6;margin:0;}}}footer{position:relative;.footer-text{font-size:18px;margin:20px 0;text-align:center;a{cursor:pointer;color:#447bff;}img{width:25px;vertical-align:sub;}}}"]),J=Y.a.span.withConfig({displayName:"styles__ForkGithub",componentId:"sc-41lvd1-1"})(['position:fixed;display:block;top:0;right:0;width:200px;overflow:hidden;height:200px;z-index:9999;.fork-link{background:#cc5739;color:#fff;text-decoration:none;text-align:center;font-weight:bold;padding:5px 40px;font-size:1rem;line-height:2rem;position:absolute;transition:0.5s;width:200px;top:60px;right:-60px;transform:rotate(45deg);&:hover{background:#7d0505;}&::before,&::after{content:"";width:100%;display:block;position:absolute;top:1px;left:0;height:1px;background:#fff;}&::after{bottom:1px;top:auto;}}']);e.default=function(){return i.a.createElement(i.a.Fragment,null,i.a.createElement(J,null,i.a.createElement("a",{className:"fork-link",href:"https://github.com/kis/chartify",target:"_blank"},"Fork me on GitHub")),i.a.createElement(H,null,i.a.createElement("header",{className:"container"},i.a.createElement("div",{className:"project-title"},i.a.createElement("h2",{className:"main-header"},"Chartify"),i.a.createElement("h4",{className:"sub-header"},"React.js plugin for building customizable charts"))),i.a.createElement("main",{className:"container"},i.a.createElement(w.a,{store:W},i.a.createElement(V,null))),i.a.createElement("footer",{className:"container"},i.a.createElement("div",{className:"footer-text"},"Made with ",i.a.createElement("img",{src:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Love_Heart_symbol.svg/2000px-Love_Heart_symbol.svg.png",title:"love"})," Inspired by ",i.a.createElement("a",{href:"http://kinopoisk.ru",target:"_blank"},"kinopoisk")))))}},68:function(t,e,n){var r;window,t.exports=(r=n(542),function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=147)}([function(t,e,n){var r=n(2),o=n(16).f,i=n(14),a=n(17),c=n(82),u=n(106),s=n(54);t.exports=function(t,e){var n,f,l,d,p,h=t.target,v=t.global,g=t.stat;if(n=v?r:g?r[h]||c(h,{}):(r[h]||{}).prototype)for(f in e){if(d=e[f],l=t.noTargetGet?(p=o(n,f))&&p.value:n[f],!s(v?f:h+(g?".":"#")+f,t.forced)&&void 0!==l){if(typeof d==typeof l)continue;u(d,l)}(t.sham||l&&l.sham)&&i(d,"sham",!0),a(n,f,d,t)}}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){(function(e){var n="object",r=function(t){return t&&t.Math==Math&&t};t.exports=r(typeof globalThis==n&&globalThis)||r(typeof window==n&&window)||r(typeof self==n&&self)||r(typeof e==n&&e)||Function("return this")()}).call(this,n(155))},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){var r=n(3);t.exports=function(t){if(!r(t))throw TypeError(String(t)+" is not an object");return t}},function(t,e,n){"use strict";var r,o=n(6),i=n(2),a=n(3),c=n(12),u=n(61),s=n(14),f=n(17),l=n(9).f,d=n(28),p=n(45),h=n(7),v=n(51),g=i.DataView,y=g&&g.prototype,b=i.Int8Array,m=b&&b.prototype,x=i.Uint8ClampedArray,w=x&&x.prototype,D=b&&d(b),I=m&&d(m),M=Object.prototype,S=M.isPrototypeOf,j=h("toStringTag"),E=v("TYPED_ARRAY_TAG"),A=!(!i.ArrayBuffer||!g),O=A&&!!p,k=!1,_={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},T=function(t){return a(t)&&c(_,u(t))};for(r in _)i[r]||(O=!1);if((!O||"function"!=typeof D||D===Function.prototype)&&(D=function(){throw TypeError("Incorrect invocation")},O))for(r in _)i[r]&&p(i[r],D);if((!O||!I||I===M)&&(I=D.prototype,O))for(r in _)i[r]&&p(i[r].prototype,I);if(O&&d(w)!==I&&p(w,I),o&&!c(I,j))for(r in k=!0,l(I,j,{get:function(){return a(this)?this[E]:void 0}}),_)i[r]&&s(i[r],E,r);A&&p&&d(y)!==M&&p(y,M),t.exports={NATIVE_ARRAY_BUFFER:A,NATIVE_ARRAY_BUFFER_VIEWS:O,TYPED_ARRAY_TAG:k&&E,aTypedArray:function(t){if(T(t))return t;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(t){if(p){if(S.call(D,t))return t}else for(var e in _)if(c(_,r)){var n=i[e];if(n&&(t===n||S.call(n,t)))return t}throw TypeError("Target is not a typed array constructor")},exportProto:function(t,e,n){if(o){if(n)for(var r in _){var a=i[r];a&&c(a.prototype,t)&&delete a.prototype[t]}I[t]&&!n||f(I,t,n?e:O&&m[t]||e)}},exportStatic:function(t,e,n){var r,a;if(o){if(p){if(n)for(r in _)(a=i[r])&&c(a,t)&&delete a[t];if(D[t]&&!n)return;try{return f(D,t,n?e:O&&b[t]||e)}catch(t){}}for(r in _)!(a=i[r])||a[t]&&!n||f(a,t,e)}},isView:function(t){var e=u(t);return"DataView"===e||c(_,e)},isTypedArray:T,TypedArray:D,TypedArrayPrototype:I}},function(t,e,n){var r=n(1);t.exports=!r(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(2),o=n(50),i=n(51),a=n(108),c=r.Symbol,u=o("wks");t.exports=function(t){return u[t]||(u[t]=a&&c[t]||(a?c:i)("Symbol."+t))}},function(t,e,n){var r=n(24),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,e,n){var r=n(6),o=n(103),i=n(4),a=n(26),c=Object.defineProperty;e.f=r?c:function(t,e,n){if(i(t),e=a(e,!0),i(n),o)try{return c(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(15);t.exports=function(t){return Object(r(t))}},function(t,e){t.exports=r},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(36),o=n(49),i=n(10),a=n(8),c=n(56),u=[].push,s=function(t){var e=1==t,n=2==t,s=3==t,f=4==t,l=6==t,d=5==t||l;return function(p,h,v,g){for(var y,b,m=i(p),x=o(m),w=r(h,v,3),D=a(x.length),I=0,M=g||c,S=e?M(p,D):n?M(p,0):void 0;D>I;I++)if((d||I in x)&&(b=w(y=x[I],I,m),t))if(e)S[I]=b;else if(b)switch(t){case 3:return!0;case 5:return y;case 6:return I;case 2:u.call(S,y)}else if(f)return!1;return l?-1:s||f?f:S}};t.exports={forEach:s(0),map:s(1),filter:s(2),some:s(3),every:s(4),find:s(5),findIndex:s(6)}},function(t,e,n){var r=n(6),o=n(9),i=n(39);t.exports=r?function(t,e,n){return o.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e){t.exports=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(6),o=n(64),i=n(39),a=n(19),c=n(26),u=n(12),s=n(103),f=Object.getOwnPropertyDescriptor;e.f=r?f:function(t,e){if(t=a(t),e=c(e,!0),s)try{return f(t,e)}catch(t){}if(u(t,e))return i(!o.f.call(t,e),t[e])}},function(t,e,n){var r=n(2),o=n(50),i=n(14),a=n(12),c=n(82),u=n(104),s=n(20),f=s.get,l=s.enforce,d=String(u).split("toString");o("inspectSource",function(t){return u.call(t)}),(t.exports=function(t,e,n,o){var u=!!o&&!!o.unsafe,s=!!o&&!!o.enumerable,f=!!o&&!!o.noTargetGet;"function"==typeof n&&("string"!=typeof e||a(n,"name")||i(n,"name",e),l(n).source=d.join("string"==typeof e?e:"")),t!==r?(u?!f&&t[e]&&(s=!0):delete t[e],s?t[e]=n:i(t,e,n)):s?t[e]=n:c(e,n)})(Function.prototype,"toString",function(){return"function"==typeof this&&f(this).source||u.call(this)})},function(t,e,n){var r=n(44),o=n(12),i=n(111),a=n(9).f;t.exports=function(t){var e=r.Symbol||(r.Symbol={});o(e,t)||a(e,t,{value:i.f(t)})}},function(t,e,n){var r=n(49),o=n(15);t.exports=function(t){return r(o(t))}},function(t,e,n){var r,o,i,a=n(105),c=n(2),u=n(3),s=n(14),f=n(12),l=n(65),d=n(52),p=c.WeakMap;if(a){var h=new p,v=h.get,g=h.has,y=h.set;r=function(t,e){return y.call(h,t,e),e},o=function(t){return v.call(h,t)||{}},i=function(t){return g.call(h,t)}}else{var b=l("state");d[b]=!0,r=function(t,e){return s(t,b,e),e},o=function(t){return f(t,b)?t[b]:{}},i=function(t){return f(t,b)}}t.exports={set:r,get:o,has:i,enforce:function(t){return i(t)?o(t):r(t,{})},getterFor:function(t){return function(e){var n;if(!u(e)||(n=o(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return n}}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(String(t)+" is not a function");return t}},function(t,e,n){var r=n(15),o=/"/g;t.exports=function(t,e,n,i){var a=String(r(t)),c="<"+e;return""!==n&&(c+=" "+n+'="'+String(i).replace(o,"&quot;")+'"'),c+">"+a+"</"+e+">"}},function(t,e,n){var r=n(1);t.exports=function(t){return r(function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3})}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(3);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(9).f,o=n(12),i=n(7)("toStringTag");t.exports=function(t,e,n){t&&!o(t=n?t:t.prototype,i)&&r(t,i,{configurable:!0,value:e})}},function(t,e,n){var r=n(12),o=n(10),i=n(65),a=n(88),c=i("IE_PROTO"),u=Object.prototype;t.exports=a?Object.getPrototypeOf:function(t){return t=o(t),r(t,c)?t[c]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,e,n){"use strict";var r=n(1);t.exports=function(t,e){var n=[][t];return!n||!r(function(){n.call(null,e||function(){throw 1},1)})}},function(t,e,n){var r=n(4),o=n(21),i=n(7)("species");t.exports=function(t,e){var n,a=r(t).constructor;return void 0===a||null==(n=r(a)[i])?e:o(n)}},function(t,e,n){"use strict";var r=n(0),o=n(2),i=n(6),a=n(101),c=n(5),u=n(79),s=n(38),f=n(39),l=n(14),d=n(8),p=n(136),h=n(137),v=n(26),g=n(12),y=n(61),b=n(3),m=n(35),x=n(45),w=n(40).f,D=n(138),I=n(13).forEach,M=n(46),S=n(9),j=n(16),E=n(20),A=E.get,O=E.set,k=S.f,_=j.f,T=Math.round,R=o.RangeError,P=u.ArrayBuffer,L=u.DataView,N=c.NATIVE_ARRAY_BUFFER_VIEWS,V=c.TYPED_ARRAY_TAG,F=c.TypedArray,U=c.TypedArrayPrototype,C=c.aTypedArrayConstructor,z=c.isTypedArray,B=function(t,e){for(var n=0,r=e.length,o=new(C(t))(r);r>n;)o[n]=e[n++];return o},q=function(t,e){k(t,e,{get:function(){return A(this)[e]}})},G=function(t){var e;return t instanceof P||"ArrayBuffer"==(e=y(t))||"SharedArrayBuffer"==e},W=function(t,e){return z(t)&&"symbol"!=typeof e&&e in t&&String(+e)==String(e)},Y=function(t,e){return W(t,e=v(e,!0))?f(2,t[e]):_(t,e)},H=function(t,e,n){return!(W(t,e=v(e,!0))&&b(n)&&g(n,"value"))||g(n,"get")||g(n,"set")||n.configurable||g(n,"writable")&&!n.writable||g(n,"enumerable")&&!n.enumerable?k(t,e,n):(t[e]=n.value,t)};i?(N||(j.f=Y,S.f=H,q(U,"buffer"),q(U,"byteOffset"),q(U,"byteLength"),q(U,"length")),r({target:"Object",stat:!0,forced:!N},{getOwnPropertyDescriptor:Y,defineProperty:H}),t.exports=function(t,e,n,i){var c=t+(i?"Clamped":"")+"Array",u="get"+t,f="set"+t,v=o[c],g=v,y=g&&g.prototype,S={},j=function(t,n){k(t,n,{get:function(){return function(t,n){var r=A(t);return r.view[u](n*e+r.byteOffset,!0)}(this,n)},set:function(t){return function(t,n,r){var o=A(t);i&&(r=(r=T(r))<0?0:r>255?255:255&r),o.view[f](n*e+o.byteOffset,r,!0)}(this,n,t)},enumerable:!0})};N?a&&(g=n(function(t,n,r,o){return s(t,g,c),b(n)?G(n)?void 0!==o?new v(n,h(r,e),o):void 0!==r?new v(n,h(r,e)):new v(n):z(n)?B(g,n):D.call(g,n):new v(p(n))}),x&&x(g,F),I(w(v),function(t){t in g||l(g,t,v[t])}),g.prototype=y):(g=n(function(t,n,r,o){s(t,g,c);var i,a,u,f=0,l=0;if(b(n)){if(!G(n))return z(n)?B(g,n):D.call(g,n);i=n,l=h(r,e);var v=n.byteLength;if(void 0===o){if(v%e)throw R("Wrong length");if((a=v-l)<0)throw R("Wrong length")}else if((a=d(o)*e)+l>v)throw R("Wrong length");u=a/e}else u=p(n),i=new P(a=u*e);for(O(t,{buffer:i,byteOffset:l,byteLength:a,length:u,view:new L(i)});f<u;)j(t,f++)}),x&&x(g,F),y=g.prototype=m(U)),y.constructor!==g&&l(y,"constructor",g),V&&l(y,V,c),S[c]=g,r({global:!0,forced:g!=v,sham:!N},S),"BYTES_PER_ELEMENT"in g||l(g,"BYTES_PER_ELEMENT",e),"BYTES_PER_ELEMENT"in y||l(y,"BYTES_PER_ELEMENT",e),M(c)}):t.exports=function(){}},function(t,e){t.exports=!1},function(t,e,n){var r=n(44),o=n(2),i=function(t){return"function"==typeof t?t:void 0};t.exports=function(t,e){return arguments.length<2?i(r[t])||i(o[t]):r[t]&&r[t][e]||o[t]&&o[t][e]}},function(t,e,n){var r=n(24),o=Math.max,i=Math.min;t.exports=function(t,e){var n=r(t);return n<0?o(n+e,0):i(n,e)}},function(t,e,n){var r=n(4),o=n(86),i=n(84),a=n(52),c=n(109),u=n(81),s=n(65)("IE_PROTO"),f=function(){},l=function(){var t,e=u("iframe"),n=i.length;for(e.style.display="none",c.appendChild(e),e.src=String("javascript:"),(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),l=t.F;n--;)delete l.prototype[i[n]];return l()};t.exports=Object.create||function(t,e){var n;return null!==t?(f.prototype=r(t),n=new f,f.prototype=null,n[s]=t):n=l(),void 0===e?n:o(n,e)},a[s]=!0},function(t,e,n){var r=n(21);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(7),o=n(35),i=n(14),a=r("unscopables"),c=Array.prototype;null==c[a]&&i(c,a,o(null)),t.exports=function(t){c[a][t]=!0}},function(t,e){t.exports=function(t,e,n){if(!(t instanceof e))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return t}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(107),o=n(84).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,o)}},function(t,e,n){var r=n(25);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,e,n){var r=n(52),o=n(3),i=n(12),a=n(9).f,c=n(51),u=n(57),s=c("meta"),f=0,l=Object.isExtensible||function(){return!0},d=function(t){a(t,s,{value:{objectID:"O"+ ++f,weakData:{}}})},p=t.exports={REQUIRED:!1,fastKey:function(t,e){if(!o(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!i(t,s)){if(!l(t))return"F";if(!e)return"E";d(t)}return t[s].objectID},getWeakData:function(t,e){if(!i(t,s)){if(!l(t))return!0;if(!e)return!1;d(t)}return t[s].weakData},onFreeze:function(t){return u&&p.REQUIRED&&l(t)&&!i(t,s)&&d(t),t}};r[s]=!0},function(t,e,n){"use strict";var r=n(26),o=n(9),i=n(39);t.exports=function(t,e,n){var a=r(e);a in t?o.f(t,a,i(0,n)):t[a]=n}},function(t,e,n){t.exports=n(2)},function(t,e,n){var r=n(4),o=n(116);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,n={};try{(t=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(n,[]),e=n instanceof Array}catch(t){}return function(n,i){return r(n),o(i),e?t.call(n,i):n.__proto__=i,n}}():void 0)},function(t,e,n){"use strict";var r=n(33),o=n(9),i=n(7),a=n(6),c=i("species");t.exports=function(t){var e=r(t),n=o.f;a&&e&&!e[c]&&n(e,c,{configurable:!0,get:function(){return this}})}},function(t,e,n){var r=n(15),o="["+n(76)+"]",i=RegExp("^"+o+o+"*"),a=RegExp(o+o+"*$"),c=function(t){return function(e){var n=String(r(e));return 1&t&&(n=n.replace(i,"")),2&t&&(n=n.replace(a,"")),n}};t.exports={start:c(1),end:c(2),trim:c(3)}},function(t,e,n){var r=n(17);t.exports=function(t,e,n){for(var o in e)r(t,o,e[o],n);return t}},function(t,e,n){var r=n(1),o=n(25),i="".split;t.exports=r(function(){return!Object("z").propertyIsEnumerable(0)})?function(t){return"String"==o(t)?i.call(t,""):Object(t)}:Object},function(t,e,n){var r=n(2),o=n(82),i=n(32),a=r["__core-js_shared__"]||o("__core-js_shared__",{});(t.exports=function(t,e){return a[t]||(a[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.1.3",mode:i?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++n+r).toString(36)}},function(t,e){t.exports={}},function(t,e,n){var r=n(19),o=n(8),i=n(34),a=function(t){return function(e,n,a){var c,u=r(e),s=o(u.length),f=i(a,s);if(t&&n!=n){for(;s>f;)if((c=u[f++])!=c)return!0}else for(;s>f;f++)if((t||f in u)&&u[f]===n)return t||f||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},function(t,e,n){var r=n(1),o=/#|\.prototype\./,i=function(t,e){var n=c[a(t)];return n==s||n!=u&&("function"==typeof e?r(e):!!e)},a=i.normalize=function(t){return String(t).replace(o,".").toLowerCase()},c=i.data={},u=i.NATIVE="N",s=i.POLYFILL="P";t.exports=i},function(t,e,n){var r=n(107),o=n(84);t.exports=Object.keys||function(t){return r(t,o)}},function(t,e,n){var r=n(3),o=n(41),i=n(7)("species");t.exports=function(t,e){var n;return o(t)&&("function"!=typeof(n=t.constructor)||n!==Array&&!o(n.prototype)?r(n)&&null===(n=n[i])&&(n=void 0):n=void 0),new(void 0===n?Array:n)(0===e?0:e)}},function(t,e,n){var r=n(1);t.exports=!r(function(){return Object.isExtensible(Object.preventExtensions({}))})},function(t,e,n){var r=n(4),o=n(87),i=n(8),a=n(36),c=n(60),u=n(114),s=function(t,e){this.stopped=t,this.result=e};(t.exports=function(t,e,n,f,l){var d,p,h,v,g,y,b=a(e,n,f?2:1);if(l)d=t;else{if("function"!=typeof(p=c(t)))throw TypeError("Target is not iterable");if(o(p)){for(h=0,v=i(t.length);v>h;h++)if((g=f?b(r(y=t[h])[0],y[1]):b(t[h]))&&g instanceof s)return g;return new s(!1)}d=p.call(t)}for(;!(y=d.next()).done;)if((g=u(d,b,y.value,f))&&g instanceof s)return g;return new s(!1)}).stop=function(t){return new s(!0,t)}},function(t,e){t.exports={}},function(t,e,n){var r=n(61),o=n(59),i=n(7)("iterator");t.exports=function(t){if(null!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,e,n){var r=n(25),o=n(7)("toStringTag"),i="Arguments"==r(function(){return arguments}());t.exports=function(t){var e,n,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),o))?n:i?r(e):"Object"==(a=r(e))&&"function"==typeof e.callee?"Arguments":a}},function(t,e,n){var r=n(1),o=n(7)("species");t.exports=function(t){return!r(function(){var e=[];return(e.constructor={})[o]=function(){return{foo:1}},1!==e[t](Boolean).foo})}},function(t,e,n){"use strict";var r=n(4);t.exports=function(){var t=r(this),e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.sticky&&(e+="y"),e}},function(t,e,n){"use strict";var r={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i=o&&!r.call({1:2},1);e.f=i?function(t){var e=o(this,t);return!!e&&e.enumerable}:r},function(t,e,n){var r=n(50),o=n(51),i=r("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},function(t,e,n){"use strict";var r=n(32),o=n(2),i=n(1);t.exports=r||!i(function(){var t=Math.random();__defineSetter__.call(null,t,function(){}),delete o[t]})},function(t,e,n){var r=n(7)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[r]=function(){return this},Array.from(a,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var n=!1;try{var i={};i[r]=function(){return{next:function(){return{done:n=!0}}}},t(i)}catch(t){}return n}},function(t,e,n){var r=n(21),o=n(10),i=n(49),a=n(8),c=function(t){return function(e,n,c,u){r(n);var s=o(e),f=i(s),l=a(s.length),d=t?l-1:0,p=t?-1:1;if(c<2)for(;;){if(d in f){u=f[d],d+=p;break}if(d+=p,t?d<0:l<=d)throw TypeError("Reduce of empty array with no initial value")}for(;t?d>=0:l>d;d+=p)d in f&&(u=n(u,f[d],d,s));return u}};t.exports={left:c(!1),right:c(!0)}},function(t,e,n){"use strict";var r=n(19),o=n(37),i=n(59),a=n(20),c=n(90),u=a.set,s=a.getterFor("Array Iterator");t.exports=c(Array,"Array",function(t,e){u(this,{type:"Array Iterator",target:r(t),index:0,kind:e})},function(){var t=s(this),e=t.target,n=t.kind,r=t.index++;return!e||r>=e.length?(t.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:e[r],done:!1}:{value:[r,e[r]],done:!1}},"values"),i.Arguments=i.Array,o("keys"),o("values"),o("entries")},function(t,e,n){var r=n(24),o=n(15),i=function(t){return function(e,n){var i,a,c=String(o(e)),u=r(n),s=c.length;return u<0||u>=s?t?"":void 0:(i=c.charCodeAt(u))<55296||i>56319||u+1===s||(a=c.charCodeAt(u+1))<56320||a>57343?t?c.charAt(u):i:t?c.slice(u,u+2):a-56320+(i-55296<<10)+65536}};t.exports={codeAt:i(!1),charAt:i(!0)}},function(t,e,n){"use strict";var r=n(14),o=n(17),i=n(1),a=n(7),c=n(72),u=a("species"),s=!i(function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")}),f=!i(function(){var t=/(?:)/,e=t.exec;t.exec=function(){return e.apply(this,arguments)};var n="ab".split(t);return 2!==n.length||"a"!==n[0]||"b"!==n[1]});t.exports=function(t,e,n,l){var d=a(t),p=!i(function(){var e={};return e[d]=function(){return 7},7!=""[t](e)}),h=p&&!i(function(){var e=!1,n=/a/;return n.exec=function(){return e=!0,null},"split"===t&&(n.constructor={},n.constructor[u]=function(){return n}),n[d](""),!e});if(!p||!h||"replace"===t&&!s||"split"===t&&!f){var v=/./[d],g=n(d,""[t],function(t,e,n,r,o){return e.exec===c?p&&!o?{done:!0,value:v.call(e,n,r)}:{done:!0,value:t.call(n,e,r)}:{done:!1}}),y=g[0],b=g[1];o(String.prototype,t,y),o(RegExp.prototype,d,2==e?function(t,e){return b.call(t,this,e)}:function(t){return b.call(t,this)}),l&&r(RegExp.prototype[d],"sham",!0)}}},function(t,e,n){"use strict";var r,o,i=n(63),a=RegExp.prototype.exec,c=String.prototype.replace,u=a,s=(r=/a/,o=/b*/g,a.call(r,"a"),a.call(o,"a"),0!==r.lastIndex||0!==o.lastIndex),f=void 0!==/()??/.exec("")[1];(s||f)&&(u=function(t){var e,n,r,o,u=this;return f&&(n=new RegExp("^"+u.source+"$(?!\\s)",i.call(u))),s&&(e=u.lastIndex),r=a.call(u,t),s&&r&&(u.lastIndex=u.global?r.index+r[0].length:e),f&&r&&r.length>1&&c.call(r[0],n,function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(r[o]=void 0)}),r}),t.exports=u},function(t,e,n){"use strict";var r=n(70).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},function(t,e,n){var r=n(25),o=n(72);t.exports=function(t,e){var n=t.exec;if("function"==typeof n){var i=n.call(t,e);if("object"!=typeof i)throw TypeError("RegExp exec method returned something other than an Object or null");return i}if("RegExp"!==r(t))throw TypeError("RegExp#exec called on incompatible receiver");return o.call(t,e)}},function(t,e,n){var r=n(33);t.exports=r("navigator","userAgent")||""},function(t,e){t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},function(t,e){var n=Math.expm1,r=Math.exp;t.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||-2e-17!=n(-2e-17)?function(t){return 0==(t=+t)?t:t>-1e-6&&t<1e-6?t+t*t/2:r(t)-1}:n},function(t,e,n){"use strict";var r=n(0),o=n(2),i=n(54),a=n(17),c=n(42),u=n(58),s=n(38),f=n(3),l=n(1),d=n(67),p=n(27),h=n(98);t.exports=function(t,e,n,v,g){var y=o[t],b=y&&y.prototype,m=y,x=v?"set":"add",w={},D=function(t){var e=b[t];a(b,t,"add"==t?function(t){return e.call(this,0===t?0:t),this}:"delete"==t?function(t){return!(g&&!f(t))&&e.call(this,0===t?0:t)}:"get"==t?function(t){return g&&!f(t)?void 0:e.call(this,0===t?0:t)}:"has"==t?function(t){return!(g&&!f(t))&&e.call(this,0===t?0:t)}:function(t,n){return e.call(this,0===t?0:t,n),this})};if(i(t,"function"!=typeof y||!(g||b.forEach&&!l(function(){(new y).entries().next()}))))m=n.getConstructor(e,t,v,x),c.REQUIRED=!0;else if(i(t,!0)){var I=new m,M=I[x](g?{}:-0,1)!=I,S=l(function(){I.has(1)}),j=d(function(t){new y(t)}),E=!g&&l(function(){for(var t=new y,e=5;e--;)t[x](e,e);return!t.has(-0)});j||((m=e(function(e,n){s(e,m,t);var r=h(new y,e,m);return null!=n&&u(n,r[x],r,v),r})).prototype=b,b.constructor=m),(S||E)&&(D("delete"),D("has"),v&&D("get")),(E||M)&&D(x),g&&b.clear&&delete b.clear}return w[t]=m,r({global:!0,forced:m!=y},w),p(m,t),g||n.setStrong(m,t,v),m}},function(t,e,n){"use strict";var r=n(2),o=n(6),i=n(5).NATIVE_ARRAY_BUFFER,a=n(14),c=n(48),u=n(1),s=n(38),f=n(24),l=n(8),d=n(136),p=n(40).f,h=n(9).f,v=n(89),g=n(27),y=n(20),b=y.get,m=y.set,x=r.ArrayBuffer,w=x,D=r.DataView,I=r.Math,M=r.RangeError,S=I.abs,j=I.pow,E=I.floor,A=I.log,O=I.LN2,k=function(t,e,n){var r,o,i,a=new Array(n),c=8*n-e-1,u=(1<<c)-1,s=u>>1,f=23===e?j(2,-24)-j(2,-77):0,l=t<0||0===t&&1/t<0?1:0,d=0;for((t=S(t))!=t||t===1/0?(o=t!=t?1:0,r=u):(r=E(A(t)/O),t*(i=j(2,-r))<1&&(r--,i*=2),(t+=r+s>=1?f/i:f*j(2,1-s))*i>=2&&(r++,i/=2),r+s>=u?(o=0,r=u):r+s>=1?(o=(t*i-1)*j(2,e),r+=s):(o=t*j(2,s-1)*j(2,e),r=0));e>=8;a[d++]=255&o,o/=256,e-=8);for(r=r<<e|o,c+=e;c>0;a[d++]=255&r,r/=256,c-=8);return a[--d]|=128*l,a},_=function(t,e){var n,r=t.length,o=8*r-e-1,i=(1<<o)-1,a=i>>1,c=o-7,u=r-1,s=t[u--],f=127&s;for(s>>=7;c>0;f=256*f+t[u],u--,c-=8);for(n=f&(1<<-c)-1,f>>=-c,c+=e;c>0;n=256*n+t[u],u--,c-=8);if(0===f)f=1-a;else{if(f===i)return n?NaN:s?-1/0:1/0;n+=j(2,e),f-=a}return(s?-1:1)*n*j(2,f-e)},T=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},R=function(t){return[255&t]},P=function(t){return[255&t,t>>8&255]},L=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},N=function(t){return k(t,23,4)},V=function(t){return k(t,52,8)},F=function(t,e){h(t.prototype,e,{get:function(){return b(this)[e]}})},U=function(t,e,n,r){var o=d(+n),i=b(t);if(o+e>i.byteLength)throw M("Wrong index");var a=b(i.buffer).bytes,c=o+i.byteOffset,u=a.slice(c,c+e);return r?u:u.reverse()},C=function(t,e,n,r,o,i){var a=d(+n),c=b(t);if(a+e>c.byteLength)throw M("Wrong index");for(var u=b(c.buffer).bytes,s=a+c.byteOffset,f=r(+o),l=0;l<e;l++)u[s+l]=f[i?l:e-l-1]};if(i){if(!u(function(){x(1)})||!u(function(){new x(-1)})||u(function(){return new x,new x(1.5),new x(NaN),"ArrayBuffer"!=x.name})){for(var z,B=(w=function(t){return s(this,w),new x(d(t))}).prototype=x.prototype,q=p(x),G=0;q.length>G;)(z=q[G++])in w||a(w,z,x[z]);B.constructor=w}var W=new D(new w(2)),Y=D.prototype.setInt8;W.setInt8(0,2147483648),W.setInt8(1,2147483649),!W.getInt8(0)&&W.getInt8(1)||c(D.prototype,{setInt8:function(t,e){Y.call(this,t,e<<24>>24)},setUint8:function(t,e){Y.call(this,t,e<<24>>24)}},{unsafe:!0})}else w=function(t){s(this,w,"ArrayBuffer");var e=d(t);m(this,{bytes:v.call(new Array(e),0),byteLength:e}),o||(this.byteLength=e)},D=function(t,e,n){s(this,D,"DataView"),s(t,w,"DataView");var r=b(t).byteLength,i=f(e);if(i<0||i>r)throw M("Wrong offset");if(i+(n=void 0===n?r-i:l(n))>r)throw M("Wrong length");m(this,{buffer:t,byteLength:n,byteOffset:i}),o||(this.buffer=t,this.byteLength=n,this.byteOffset=i)},o&&(F(w,"byteLength"),F(D,"buffer"),F(D,"byteLength"),F(D,"byteOffset")),c(D.prototype,{getInt8:function(t){return U(this,1,t)[0]<<24>>24},getUint8:function(t){return U(this,1,t)[0]},getInt16:function(t){var e=U(this,2,t,arguments.length>1?arguments[1]:void 0);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=U(this,2,t,arguments.length>1?arguments[1]:void 0);return e[1]<<8|e[0]},getInt32:function(t){return T(U(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return T(U(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return _(U(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return _(U(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,e){C(this,1,t,R,e)},setUint8:function(t,e){C(this,1,t,R,e)},setInt16:function(t,e){C(this,2,t,P,e,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,e){C(this,2,t,P,e,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,e){C(this,4,t,L,e,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,e){C(this,4,t,L,e,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,e){C(this,4,t,N,e,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,e){C(this,8,t,V,e,arguments.length>2?arguments[2]:void 0)}});g(w,"ArrayBuffer"),g(D,"DataView"),e.ArrayBuffer=w,e.DataView=D},function(t,e,n){"use strict";var r,o,i,a=n(374),c="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function u(){i=!1}function s(t){if(t){if(t!==r){if(t.length!==c.length)throw new Error("Custom alphabet for shortid must be "+c.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter(function(t,e,n){return e!==n.lastIndexOf(t)});if(e.length)throw new Error("Custom alphabet for shortid must be "+c.length+" unique characters. These characters were not unique: "+e.join(", "));r=t,u()}}else r!==c&&(r=c,u())}function f(){return i||(i=function(){r||s(c);for(var t,e=r.split(""),n=[],o=a.nextValue();e.length>0;)o=a.nextValue(),t=Math.floor(o*e.length),n.push(e.splice(t,1)[0]);return n.join("")}())}t.exports={get:function(){return r||c},characters:function(t){return s(t),r},seed:function(t){a.seed(t),o!==t&&(u(),o=t)},lookup:function(t){return f()[t]},shuffled:f}},function(t,e,n){var r=n(2),o=n(3),i=r.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},function(t,e,n){var r=n(2),o=n(14);t.exports=function(t,e){try{o(r,t,e)}catch(n){r[t]=e}return e}},function(t,e,n){var r=n(33),o=n(40),i=n(85),a=n(4);t.exports=r("Reflect","ownKeys")||function(t){var e=o.f(a(t)),n=i.f;return n?e.concat(n(t)):e}},function(t,e){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,n){var r=n(6),o=n(9),i=n(4),a=n(55);t.exports=r?Object.defineProperties:function(t,e){i(t);for(var n,r=a(e),c=r.length,u=0;c>u;)o.f(t,n=r[u++],e[n]);return t}},function(t,e,n){var r=n(7),o=n(59),i=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},function(t,e,n){var r=n(1);t.exports=!r(function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})},function(t,e,n){"use strict";var r=n(10),o=n(34),i=n(8);t.exports=function(t){for(var e=r(this),n=i(e.length),a=arguments.length,c=o(a>1?arguments[1]:void 0,n),u=a>2?arguments[2]:void 0,s=void 0===u?n:o(u,n);s>c;)e[c++]=t;return e}},function(t,e,n){"use strict";var r=n(0),o=n(91),i=n(28),a=n(45),c=n(27),u=n(14),s=n(17),f=n(7),l=n(32),d=n(59),p=n(123),h=p.IteratorPrototype,v=p.BUGGY_SAFARI_ITERATORS,g=f("iterator"),y=function(){return this};t.exports=function(t,e,n,f,p,b,m){o(n,e,f);var x,w,D,I=function(t){if(t===p&&A)return A;if(!v&&t in j)return j[t];switch(t){case"keys":case"values":case"entries":return function(){return new n(this,t)}}return function(){return new n(this)}},M=e+" Iterator",S=!1,j=t.prototype,E=j[g]||j["@@iterator"]||p&&j[p],A=!v&&E||I(p),O="Array"==e&&j.entries||E;if(O&&(x=i(O.call(new t)),h!==Object.prototype&&x.next&&(l||i(x)===h||(a?a(x,h):"function"!=typeof x[g]&&u(x,g,y)),c(x,M,!0,!0),l&&(d[M]=y))),"values"==p&&E&&"values"!==E.name&&(S=!0,A=function(){return E.call(this)}),l&&!m||j[g]===A||u(j,g,A),d[e]=A,p)if(w={values:I("values"),keys:b?A:I("keys"),entries:I("entries")},m)for(D in w)!v&&!S&&D in j||s(j,D,w[D]);else r({target:e,proto:!0,forced:v||S},w);return w}},function(t,e,n){"use strict";var r=n(123).IteratorPrototype,o=n(35),i=n(39),a=n(27),c=n(59),u=function(){return this};t.exports=function(t,e,n){var s=e+" Iterator";return t.prototype=o(r,{next:i(1,n)}),a(t,s,!1,!0),c[s]=u,t}},function(t,e,n){var r=n(93);t.exports=function(t){if(r(t))throw TypeError("The method doesn't accept regular expressions");return t}},function(t,e,n){var r=n(3),o=n(25),i=n(7)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[i])?!!e:"RegExp"==o(t))}},function(t,e,n){var r=n(7)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,"/./"[t](e)}catch(t){}}return!1}},function(t,e,n){var r=n(8),o=n(96),i=n(15),a=Math.ceil,c=function(t){return function(e,n,c){var u,s,f=String(i(e)),l=f.length,d=void 0===c?" ":String(c),p=r(n);return p<=l||""==d?f:(u=p-l,(s=o.call(d,a(u/d.length))).length>u&&(s=s.slice(0,u)),t?f+s:s+f)}};t.exports={start:c(!1),end:c(!0)}},function(t,e,n){"use strict";var r=n(24),o=n(15);t.exports="".repeat||function(t){var e=String(o(this)),n="",i=r(t);if(i<0||i==1/0)throw RangeError("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(e+=e))1&i&&(n+=e);return n}},function(t,e,n){var r=n(1),o=n(76);t.exports=function(t){return r(function(){return!!o[t]()||"​…᠎"!="​…᠎"[t]()||o[t].name!==t})}},function(t,e,n){var r=n(3),o=n(45);t.exports=function(t,e,n){var i,a;return o&&"function"==typeof(i=e.constructor)&&i!==n&&r(a=i.prototype)&&a!==n.prototype&&o(t,a),t}},function(t,e){t.exports=Math.sign||function(t){return 0==(t=+t)||t!=t?t:t<0?-1:1}},function(t,e,n){var r,o,i,a=n(2),c=n(1),u=n(25),s=n(36),f=n(109),l=n(81),d=a.location,p=a.setImmediate,h=a.clearImmediate,v=a.process,g=a.MessageChannel,y=a.Dispatch,b=0,m={},x=function(t){if(m.hasOwnProperty(t)){var e=m[t];delete m[t],e()}},w=function(t){return function(){x(t)}},D=function(t){x(t.data)},I=function(t){a.postMessage(t+"",d.protocol+"//"+d.host)};p&&h||(p=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return m[++b]=function(){("function"==typeof t?t:Function(t)).apply(void 0,e)},r(b),b},h=function(t){delete m[t]},"process"==u(v)?r=function(t){v.nextTick(w(t))}:y&&y.now?r=function(t){y.now(w(t))}:g?(i=(o=new g).port2,o.port1.onmessage=D,r=s(i.postMessage,i,1)):!a.addEventListener||"function"!=typeof postMessage||a.importScripts||c(I)?r="onreadystatechange"in l("script")?function(t){f.appendChild(l("script")).onreadystatechange=function(){f.removeChild(this),x(t)}}:function(t){setTimeout(w(t),0)}:(r=I,a.addEventListener("message",D,!1))),t.exports={set:p,clear:h}},function(t,e,n){var r=n(2),o=n(1),i=n(67),a=n(5).NATIVE_ARRAY_BUFFER_VIEWS,c=r.ArrayBuffer,u=r.Int8Array;t.exports=!a||!o(function(){u(1)})||!o(function(){new u(-1)})||!i(function(t){new u,new u(null),new u(1.5),new u(t)},!0)||o(function(){return 1!==new u(new c(2),1,void 0).length})},function(t,e,n){"use strict";t.exports=n(373)},function(t,e,n){var r=n(6),o=n(1),i=n(81);t.exports=!r&&!o(function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(50);t.exports=r("native-function-to-string",Function.toString)},function(t,e,n){var r=n(2),o=n(104),i=r.WeakMap;t.exports="function"==typeof i&&/native code/.test(o.call(i))},function(t,e,n){var r=n(12),o=n(83),i=n(16),a=n(9);t.exports=function(t,e){for(var n=o(e),c=a.f,u=i.f,s=0;s<n.length;s++){var f=n[s];r(t,f)||c(t,f,u(e,f))}}},function(t,e,n){var r=n(12),o=n(19),i=n(53).indexOf,a=n(52);t.exports=function(t,e){var n,c=o(t),u=0,s=[];for(n in c)!r(a,n)&&r(c,n)&&s.push(n);for(;e.length>u;)r(c,n=e[u++])&&(~i(s,n)||s.push(n));return s}},function(t,e,n){var r=n(1);t.exports=!!Object.getOwnPropertySymbols&&!r(function(){return!String(Symbol())})},function(t,e,n){var r=n(33);t.exports=r("document","documentElement")},function(t,e,n){var r=n(19),o=n(40).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return a&&"[object Window]"==i.call(t)?function(t){try{return o(t)}catch(t){return a.slice()}}(t):o(r(t))}},function(t,e,n){e.f=n(7)},function(t,e,n){"use strict";var r=n(6),o=n(1),i=n(55),a=n(85),c=n(64),u=n(10),s=n(49),f=Object.assign;t.exports=!f||o(function(){var t={},e={},n=Symbol();return t[n]=7,"abcdefghijklmnopqrst".split("").forEach(function(t){e[t]=t}),7!=f({},t)[n]||"abcdefghijklmnopqrst"!=i(f({},e)).join("")})?function(t,e){for(var n=u(t),o=arguments.length,f=1,l=a.f,d=c.f;o>f;)for(var p,h=s(arguments[f++]),v=l?i(h).concat(l(h)):i(h),g=v.length,y=0;g>y;)p=v[y++],r&&!d.call(h,p)||(n[p]=h[p]);return n}:f},function(t,e,n){var r=n(6),o=n(55),i=n(19),a=n(64).f,c=function(t){return function(e){for(var n,c=i(e),u=o(c),s=u.length,f=0,l=[];s>f;)n=u[f++],r&&!a.call(c,n)||l.push(t?[n,c[n]]:c[n]);return l}};t.exports={entries:c(!0),values:c(!1)}},function(t,e,n){var r=n(4);t.exports=function(t,e,n,o){try{return o?e(r(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&r(i.call(t)),e}}},function(t,e){t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},function(t,e,n){var r=n(3);t.exports=function(t){if(!r(t)&&null!==t)throw TypeError("Can't set "+String(t)+" as a prototype");return t}},function(t,e,n){"use strict";var r=n(21),o=n(3),i=[].slice,a={},c=function(t,e,n){if(!(e in a)){for(var r=[],o=0;o<e;o++)r[o]="a["+o+"]";a[e]=Function("C,a","return new C("+r.join(",")+")")}return a[e](t,n)};t.exports=Function.bind||function(t){var e=r(this),n=i.call(arguments,1),a=function(){var r=n.concat(i.call(arguments));return this instanceof a?c(e,r.length,r):e.apply(t,r)};return o(e.prototype)&&(a.prototype=e.prototype),a}},function(t,e,n){"use strict";var r=n(36),o=n(10),i=n(114),a=n(87),c=n(8),u=n(43),s=n(60);t.exports=function(t){var e,n,f,l,d=o(t),p="function"==typeof this?this:Array,h=arguments.length,v=h>1?arguments[1]:void 0,g=void 0!==v,y=0,b=s(d);if(g&&(v=r(v,h>2?arguments[2]:void 0,2)),null==b||p==Array&&a(b))for(n=new p(e=c(d.length));e>y;y++)u(n,y,g?v(d[y],y):d[y]);else for(l=b.call(d),n=new p;!(f=l.next()).done;y++)u(n,y,g?i(l,v,[f.value,y],!0):f.value);return n.length=y,n}},function(t,e,n){"use strict";var r=n(10),o=n(34),i=n(8),a=Math.min;t.exports=[].copyWithin||function(t,e){var n=r(this),c=i(n.length),u=o(t,c),s=o(e,c),f=arguments.length>2?arguments[2]:void 0,l=a((void 0===f?c:o(f,c))-s,c-u),d=1;for(s<u&&u<s+l&&(d=-1,s+=l-1,u+=l-1);l-- >0;)s in n?n[u]=n[s]:delete n[u],u+=d,s+=d;return n}},function(t,e,n){"use strict";var r=n(41),o=n(8),i=n(36),a=function(t,e,n,c,u,s,f,l){for(var d,p=u,h=0,v=!!f&&i(f,l,3);h<c;){if(h in n){if(d=v?v(n[h],h,e):n[h],s>0&&r(d))p=a(t,e,d,o(d.length),p,s-1)-1;else{if(p>=9007199254740991)throw TypeError("Exceed the acceptable array length");t[p]=d}p++}h++}return p};t.exports=a},function(t,e,n){"use strict";var r=n(13).forEach,o=n(29);t.exports=o("forEach")?function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}:[].forEach},function(t,e,n){"use strict";var r=n(19),o=n(24),i=n(8),a=n(29),c=Math.min,u=[].lastIndexOf,s=!!u&&1/[1].lastIndexOf(1,-0)<0,f=a("lastIndexOf");t.exports=s||f?function(t){if(s)return u.apply(this,arguments)||0;var e=r(this),n=i(e.length),a=n-1;for(arguments.length>1&&(a=c(a,o(arguments[1]))),a<0&&(a=n+a);a>=0;a--)if(a in e&&e[a]===t)return a||0;return-1}:u},function(t,e,n){"use strict";var r,o,i,a=n(28),c=n(14),u=n(12),s=n(7),f=n(32),l=s("iterator"),d=!1;[].keys&&("next"in(i=[].keys())?(o=a(a(i)))!==Object.prototype&&(r=o):d=!0),null==r&&(r={}),f||u(r,l)||c(r,l,function(){return this}),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:d}},function(t,e,n){var r=n(75);t.exports=/Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(r)},function(t,e,n){"use strict";var r=n(70).charAt,o=n(20),i=n(90),a=o.set,c=o.getterFor("String Iterator");i(String,"String",function(t){a(this,{type:"String Iterator",string:String(t),index:0})},function(){var t,e=c(this),n=e.string,o=e.index;return o>=n.length?{value:void 0,done:!0}:(t=r(n,o),e.index+=t.length,{value:t,done:!1})})},function(t,e,n){var r=n(2),o=n(47).trim,i=n(76),a=r.parseInt,c=/^[+-]?0[Xx]/,u=8!==a(i+"08")||22!==a(i+"0x16");t.exports=u?function(t,e){var n=o(String(t));return a(n,e>>>0||(c.test(n)?16:10))}:a},function(t,e,n){var r=n(2),o=n(47).trim,i=n(76),a=r.parseFloat,c=1/a(i+"-0")!=-1/0;t.exports=c?function(t){var e=o(String(t)),n=a(e);return 0===n&&"-"==e.charAt(0)?-0:n}:a},function(t,e,n){var r=n(3),o=Math.floor;t.exports=function(t){return!r(t)&&isFinite(t)&&o(t)===t}},function(t,e,n){var r=n(25);t.exports=function(t){if("number"!=typeof t&&"Number"!=r(t))throw TypeError("Incorrect invocation");return+t}},function(t,e){var n=Math.log;t.exports=Math.log1p||function(t){return(t=+t)>-1e-8&&t<1e-8?t-t*t/2:n(1+t)}},function(t,e,n){var r,o,i,a,c,u,s,f=n(2),l=n(16).f,d=n(25),p=n(100).set,h=n(75),v=f.MutationObserver||f.WebKitMutationObserver,g=f.process,y=f.Promise,b="process"==d(g),m=l(f,"queueMicrotask"),x=m&&m.value;x||(r=function(){var t,e;for(b&&(t=g.domain)&&t.exit();o;){e=o.fn,o=o.next;try{e()}catch(t){throw o?a():i=void 0,t}}i=void 0,t&&t.enter()},b?a=function(){g.nextTick(r)}:v&&!/(iphone|ipod|ipad).*applewebkit/i.test(h)?(c=!0,u=document.createTextNode(""),new v(r).observe(u,{characterData:!0}),a=function(){u.data=c=!c}):y&&y.resolve?(s=y.resolve(void 0),a=function(){s.then(r)}):a=function(){p.call(f,r)}),t.exports=x||function(t){var e={fn:t,next:void 0};i&&(i.next=e),o||(o=e,a()),i=e}},function(t,e,n){var r=n(4),o=n(3),i=n(133);t.exports=function(t,e){if(r(t),o(e)&&e.constructor===t)return e;var n=i.f(t);return(0,n.resolve)(e),n.promise}},function(t,e,n){"use strict";var r=n(21),o=function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=r(e),this.reject=r(n)};t.exports.f=function(t){return new o(t)}},function(t,e,n){"use strict";var r=n(9).f,o=n(35),i=n(48),a=n(36),c=n(38),u=n(58),s=n(90),f=n(46),l=n(6),d=n(42).fastKey,p=n(20),h=p.set,v=p.getterFor;t.exports={getConstructor:function(t,e,n,s){var f=t(function(t,r){c(t,f,e),h(t,{type:e,index:o(null),first:void 0,last:void 0,size:0}),l||(t.size=0),null!=r&&u(r,t[s],t,n)}),p=v(e),g=function(t,e,n){var r,o,i=p(t),a=y(t,e);return a?a.value=n:(i.last=a={index:o=d(e,!0),key:e,value:n,previous:r=i.last,next:void 0,removed:!1},i.first||(i.first=a),r&&(r.next=a),l?i.size++:t.size++,"F"!==o&&(i.index[o]=a)),t},y=function(t,e){var n,r=p(t),o=d(e);if("F"!==o)return r.index[o];for(n=r.first;n;n=n.next)if(n.key==e)return n};return i(f.prototype,{clear:function(){for(var t=p(this),e=t.index,n=t.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete e[n.index],n=n.next;t.first=t.last=void 0,l?t.size=0:this.size=0},delete:function(t){var e=p(this),n=y(this,t);if(n){var r=n.next,o=n.previous;delete e.index[n.index],n.removed=!0,o&&(o.next=r),r&&(r.previous=o),e.first==n&&(e.first=r),e.last==n&&(e.last=o),l?e.size--:this.size--}return!!n},forEach:function(t){for(var e,n=p(this),r=a(t,arguments.length>1?arguments[1]:void 0,3);e=e?e.next:n.first;)for(r(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!y(this,t)}}),i(f.prototype,n?{get:function(t){var e=y(this,t);return e&&e.value},set:function(t,e){return g(this,0===t?0:t,e)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),l&&r(f.prototype,"size",{get:function(){return p(this).size}}),f},setStrong:function(t,e,n){var r=e+" Iterator",o=v(e),i=v(r);s(t,e,function(t,e){h(this,{type:r,target:t,state:o(t),kind:e,last:void 0})},function(){for(var t=i(this),e=t.kind,n=t.last;n&&n.removed;)n=n.previous;return t.target&&(t.last=n=n?n.next:t.state.first)?"keys"==e?{value:n.key,done:!1}:"values"==e?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:(t.target=void 0,{value:void 0,done:!0})},n?"entries":"values",!n,!0),f(e)}}},function(t,e,n){"use strict";var r=n(48),o=n(42).getWeakData,i=n(4),a=n(3),c=n(38),u=n(58),s=n(13),f=n(12),l=n(20),d=l.set,p=l.getterFor,h=s.find,v=s.findIndex,g=0,y=function(t){return t.frozen||(t.frozen=new b)},b=function(){this.entries=[]},m=function(t,e){return h(t.entries,function(t){return t[0]===e})};b.prototype={get:function(t){var e=m(this,t);if(e)return e[1]},has:function(t){return!!m(this,t)},set:function(t,e){var n=m(this,t);n?n[1]=e:this.entries.push([t,e])},delete:function(t){var e=v(this.entries,function(e){return e[0]===t});return~e&&this.entries.splice(e,1),!!~e}},t.exports={getConstructor:function(t,e,n,s){var l=t(function(t,r){c(t,l,e),d(t,{type:e,id:g++,frozen:void 0}),null!=r&&u(r,t[s],t,n)}),h=p(e),v=function(t,e,n){var r=h(t),a=o(i(e),!0);return!0===a?y(r).set(e,n):a[r.id]=n,t};return r(l.prototype,{delete:function(t){var e=h(this);if(!a(t))return!1;var n=o(t);return!0===n?y(e).delete(t):n&&f(n,e.id)&&delete n[e.id]},has:function(t){var e=h(this);if(!a(t))return!1;var n=o(t);return!0===n?y(e).has(t):n&&f(n,e.id)}}),r(l.prototype,n?{get:function(t){var e=h(this);if(a(t)){var n=o(t);return!0===n?y(e).get(t):n?n[e.id]:void 0}},set:function(t,e){return v(this,t,e)}}:{add:function(t){return v(this,t,!0)}}),l}}},function(t,e,n){var r=n(24),o=n(8);t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=o(e);if(e!==n)throw RangeError("Wrong length or index");return n}},function(t,e,n){var r=n(24);t.exports=function(t,e){var n=r(t);if(n<0||n%e)throw RangeError("Wrong offset");return n}},function(t,e,n){var r=n(10),o=n(8),i=n(60),a=n(87),c=n(36),u=n(5).aTypedArrayConstructor;t.exports=function(t){var e,n,s,f,l,d=r(t),p=arguments.length,h=p>1?arguments[1]:void 0,v=void 0!==h,g=i(d);if(null!=g&&!a(g))for(l=g.call(d),d=[];!(f=l.next()).done;)d.push(f.value);for(v&&p>2&&(h=c(h,arguments[2],2)),n=o(d.length),s=new(u(this))(n),e=0;n>e;e++)s[e]=v?h(d[e],e):d[e];return s}},function(t,e){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(t,e,n){var r=n(1),o=n(7),i=n(32),a=o("iterator");t.exports=!r(function(){var t=new URL("b?e=1","http://a"),e=t.searchParams;return t.pathname="c%20d",i&&!t.toJSON||!e.sort||"http://a/c%20d?e=1"!==t.href||"1"!==e.get("e")||"a=1"!==String(new URLSearchParams("?a=1"))||!e[a]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash})},function(t,e,n){"use strict";n(69);var r=n(0),o=n(140),i=n(17),a=n(48),c=n(27),u=n(91),s=n(20),f=n(38),l=n(12),d=n(36),p=n(4),h=n(3),v=n(370),g=n(60),y=n(7)("iterator"),b=s.set,m=s.getterFor("URLSearchParams"),x=s.getterFor("URLSearchParamsIterator"),w=/\+/g,D=Array(4),I=function(t){return D[t-1]||(D[t-1]=RegExp("((?:%[\\da-f]{2}){"+t+"})","gi"))},M=function(t){try{return decodeURIComponent(t)}catch(e){return t}},S=function(t){var e=t.replace(w," "),n=4;try{return decodeURIComponent(e)}catch(t){for(;n;)e=e.replace(I(n--),M);return e}},j=/[!'()~]|%20/g,E={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},A=function(t){return E[t]},O=function(t){return encodeURIComponent(t).replace(j,A)},k=function(t,e){if(e)for(var n,r,o=e.split("&"),i=0;i<o.length;)(n=o[i++]).length&&(r=n.split("="),t.push({key:S(r.shift()),value:S(r.join("="))}))},_=function(t){this.entries.length=0,k(this.entries,t)},T=function(t,e){if(t<e)throw TypeError("Not enough arguments")},R=u(function(t,e){b(this,{type:"URLSearchParamsIterator",iterator:v(m(t).entries),kind:e})},"Iterator",function(){var t=x(this),e=t.kind,n=t.iterator.next(),r=n.value;return n.done||(n.value="keys"===e?r.key:"values"===e?r.value:[r.key,r.value]),n}),P=function(){f(this,P,"URLSearchParams");var t,e,n,r,o,i,a,c=arguments.length>0?arguments[0]:void 0,u=this,s=[];if(b(u,{type:"URLSearchParams",entries:s,updateURL:function(){},updateSearchParams:_}),void 0!==c)if(h(c))if("function"==typeof(t=g(c)))for(e=t.call(c);!(n=e.next()).done;){if((o=(r=v(p(n.value))).next()).done||(i=r.next()).done||!r.next().done)throw TypeError("Expected sequence with length 2");s.push({key:o.value+"",value:i.value+""})}else for(a in c)l(c,a)&&s.push({key:a,value:c[a]+""});else k(s,"string"==typeof c?"?"===c.charAt(0)?c.slice(1):c:c+"")},L=P.prototype;a(L,{append:function(t,e){T(arguments.length,2);var n=m(this);n.entries.push({key:t+"",value:e+""}),n.updateURL()},delete:function(t){T(arguments.length,1);for(var e=m(this),n=e.entries,r=t+"",o=0;o<n.length;)n[o].key===r?n.splice(o,1):o++;e.updateURL()},get:function(t){T(arguments.length,1);for(var e=m(this).entries,n=t+"",r=0;r<e.length;r++)if(e[r].key===n)return e[r].value;return null},getAll:function(t){T(arguments.length,1);for(var e=m(this).entries,n=t+"",r=[],o=0;o<e.length;o++)e[o].key===n&&r.push(e[o].value);return r},has:function(t){T(arguments.length,1);for(var e=m(this).entries,n=t+"",r=0;r<e.length;)if(e[r++].key===n)return!0;return!1},set:function(t,e){T(arguments.length,1);for(var n,r=m(this),o=r.entries,i=!1,a=t+"",c=e+"",u=0;u<o.length;u++)(n=o[u]).key===a&&(i?o.splice(u--,1):(i=!0,n.value=c));i||o.push({key:a,value:c}),r.updateURL()},sort:function(){var t,e,n,r=m(this),o=r.entries,i=o.slice();for(o.length=0,n=0;n<i.length;n++){for(t=i[n],e=0;e<n;e++)if(o[e].key>t.key){o.splice(e,0,t);break}e===n&&o.push(t)}r.updateURL()},forEach:function(t){for(var e,n=m(this).entries,r=d(t,arguments.length>1?arguments[1]:void 0,3),o=0;o<n.length;)r((e=n[o++]).value,e.key,this)},keys:function(){return new R(this,"keys")},values:function(){return new R(this,"values")},entries:function(){return new R(this,"entries")}},{enumerable:!0}),i(L,y,L.entries),i(L,"toString",function(){for(var t,e=m(this).entries,n=[],r=0;r<e.length;)t=e[r++],n.push(O(t.key)+"="+O(t.value));return n.join("&")},{enumerable:!0}),c(P,"URLSearchParams"),r({global:!0,forced:!o},{URLSearchParams:P}),t.exports={URLSearchParams:P,getState:m}},function(t,e){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}},function(t,e){function n(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}t.exports=function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}},function(t,e,n){var r=n(149),o=n(150);t.exports=function(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?o(t):e}},function(t,e){function n(e){return t.exports=n=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},n(e)}t.exports=n},function(t,e,n){var r=n(151);t.exports=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&r(t,e)}},function(t,e,n){t.exports=n(148)},function(t,e,n){"use strict";n.r(e),n.d(e,"default",function(){return y});var r=n(142),o=n.n(r),i=n(143),a=n.n(i),c=n(144),u=n.n(c),s=n(145),f=n.n(s),l=n(146),d=n.n(l),p=(n(152),n(372),n(11)),h=n.n(p),v=n(102),g=n.n(v),y=(n(381),function(t){function e(){return o()(this,e),u()(this,f()(e).apply(this,arguments))}return d()(e,t),a()(e,[{key:"getStyles",value:function(t,e,n){var r=t.boxSize,o=void 0===r?20:r,i=t.bordered,a=void 0!==i&&i;return{width:"".concat(o,"px"),height:"".concat(n?o:o*(e-1),"px"),borderTop:a?"1px solid rgba(249,250,249, 0.9)":"transparent",borderLeft:a?"1px solid rgba(249,250,249, 0.9)":"transparent"}}},{key:"calcLineStyles",value:function(t,e){var n=this.props.config.boxSize,r=void 0===n?20:n,o=r,i=Math.abs(e-t)*r,a=Math.hypot(o,i),c=this.calcLineAngle(i,a,e,t);return{width:"".concat(a,"px"),transform:"rotate(".concat(c,"deg)"),top:"".concat(parseInt(r/2,10),"px"),left:"".concat(parseInt(r/2,10),"px")}}},{key:"calcLineAngle",value:function(t,e,n,r){var o=Math.fround(180*Math.asin(t/e)/Math.PI);return n>r&&(o=-o),o}},{key:"calculateMaxYValue",value:function(t){var e=t.map(function(t){return t.yValue}),n=Math.max.apply(null,e),r=(n=Math.round(n)).toString().length;r=(r-=1)||1;var o=Math.pow(10,r);return n=Math.round(n/o)*o}},{key:"renderYAxis",value:function(t,e){return h.a.createElement("div",{className:"y-axis-wrapper"},h.a.createElement("div",{className:"y-axis"},t.map(function(t,n){return h.a.createElement("div",{className:"y-caption",key:n},n%2==0?e-t.yValue:null)})))}},{key:"renderTooltip",value:function(t,e){var n={top:e<this.props.config.height/2?"-100px":0};return h.a.createElement("div",{className:"tooltiptext",style:n},h.a.createElement("div",{className:"value"},t.yValue),h.a.createElement("div",null,t.title),h.a.createElement("div",{className:"date"},t.xValue))}},{key:"renderColumn",value:function(t,e,n,r){var o=this.props.config,i=o.height,a=void 0===i?10:i,c=o.isLineChart,u=void 0!==c&&c,s=Math.round(e.yValue*a/r),f=s=s||1;t[n+1]&&(f=(f=Math.round(t[n+1].yValue*a/r))||1);var l=this.getStyles(o,s,!0),d=this.getStyles(o,s,!1);return h.a.createElement(h.a.Fragment,null,h.a.createElement("div",{key:g.a.generate(),style:d,className:"mark painted ".concat(u?"white":"")}),h.a.createElement("div",{key:g.a.generate(),style:l,className:"mark active ".concat(u?"white":"")},this.renderMarkTools(e,u,s,f)))}},{key:"renderMarkTools",value:function(t,e,n,r){var o=e?this.calcLineStyles(n,r):null;return h.a.createElement(h.a.Fragment,null,e?h.a.createElement("div",{className:"line",style:o}):null,this.renderTooltip(t,n))}},{key:"renderXAxis",value:function(t,e){var n=this.props.config.boxSize,r=void 0===n?20:n,o=t.reduce(function(t,e,n){return n%10==0?t+1:t},0),i=parseInt(t.length*r/o,10),a={width:"".concat(i,"px")};return h.a.createElement("div",{className:"x-axis",style:e},t.map(function(t,e){return e%10==0?h.a.createElement("div",{className:"x-caption",style:a,key:e},t.xValue):null}))}},{key:"renderMarks",value:function(t,e,n){var r=this;return h.a.createElement("div",{className:"marks",style:e},t.map(function(e,o){return h.a.createElement("div",{className:"ruler-row",key:o},r.renderColumn(t,e,o,n))}))}},{key:"render",value:function(){var t=this.props,e=t.data,n=void 0===e?[]:e,r=t.config,o=t.container,i=r.height,a=void 0===i?10:i,c=r.theme,u=void 0===c?"default":c,s=r.boxSize,f=void 0===s?20:s;if(!n||!n.length)return h.a.createElement("h2",null,"No dataset");var l=n.slice(0,r.width),d=this.calculateMaxYValue(l),p=Array(a).fill(0).map(function(t,e){return{yValue:Math.round(e*(d/a))}}),v="ruler-container ".concat(o," ").concat(u),g=l.length*f,y={width:"".concat(g||750,"px")},b={width:"".concat(g+50||750,"px")};return h.a.createElement("div",{className:v,style:b},this.renderYAxis(p,d),h.a.createElement("div",{className:"marks-wrapper"},this.renderMarks(l,y,d),this.renderXAxis(l,y)))}}]),e}(p.Component))},function(t,e){function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function r(e){return"function"==typeof Symbol&&"symbol"===n(Symbol.iterator)?t.exports=r=function(t){return n(t)}:t.exports=r=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":n(t)},r(e)}t.exports=r},function(t,e){t.exports=function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}},function(t,e){function n(e,r){return t.exports=n=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},n(e,r)}t.exports=n},function(t,e,n){n(153),n(362),t.exports=n(44)},function(t,e,n){n(154),n(156),n(157),n(158),n(159),n(160),n(161),n(162),n(163),n(164),n(165),n(166),n(167),n(168),n(169),n(170),n(171),n(172),n(173),n(174),n(175),n(176),n(177),n(178),n(179),n(180),n(181),n(182),n(183),n(184),n(185),n(186),n(187),n(188),n(189),n(190),n(192),n(193),n(194),n(195),n(196),n(197),n(198),n(199),n(200),n(201),n(202),n(203),n(204),n(205),n(206),n(207),n(208),n(209),n(210),n(211),n(212),n(213),n(214),n(215),n(216),n(217),n(218),n(219),n(220),n(221),n(222),n(223),n(224),n(225),n(226),n(69),n(227),n(228),n(229),n(230),n(231),n(232),n(233),n(234),n(235),n(236),n(237),n(238),n(239),n(240),n(241),n(242),n(243),n(125),n(244),n(245),n(246),n(247),n(248),n(249),n(250),n(251),n(252),n(253),n(254),n(255),n(256),n(257),n(258),n(259),n(260),n(261),n(262),n(263),n(264),n(265),n(267),n(268),n(269),n(270),n(271),n(272),n(273),n(274),n(275),n(276),n(277),n(278),n(279),n(280),n(281),n(282),n(283),n(285),n(286),n(287),n(288),n(289),n(290),n(291),n(292),n(293),n(294),n(295),n(296),n(297),n(299),n(300),n(302),n(303),n(306),n(307),n(308),n(309),n(310),n(311),n(312),n(313),n(314),n(315),n(316),n(317),n(318),n(319),n(320),n(321),n(322),n(323),n(324),n(325),n(326),n(327),n(328),n(329),n(330),n(331),n(332),n(333),n(334),n(335),n(336),n(337),n(338),n(339),n(340),n(341),n(342),n(343),n(344),n(345),n(346),n(347),n(348),n(349),n(350),n(351),n(352),n(353),n(354),n(355),n(356),n(357),n(358),n(359),n(360),n(361),t.exports=n(44)},function(t,e,n){"use strict";var r=n(0),o=n(2),i=n(32),a=n(6),c=n(108),u=n(1),s=n(12),f=n(41),l=n(3),d=n(4),p=n(10),h=n(19),v=n(26),g=n(39),y=n(35),b=n(55),m=n(40),x=n(110),w=n(85),D=n(16),I=n(9),M=n(64),S=n(14),j=n(17),E=n(50),A=n(65),O=n(52),k=n(51),_=n(7),T=n(111),R=n(18),P=n(27),L=n(20),N=n(13).forEach,V=A("hidden"),F=_("toPrimitive"),U=L.set,C=L.getterFor("Symbol"),z=Object.prototype,B=o.Symbol,q=o.JSON,G=q&&q.stringify,W=D.f,Y=I.f,H=x.f,J=M.f,X=E("symbols"),$=E("op-symbols"),K=E("string-to-symbol-registry"),Q=E("symbol-to-string-registry"),Z=E("wks"),tt=o.QObject,et=!tt||!tt.prototype||!tt.prototype.findChild,nt=a&&u(function(){return 7!=y(Y({},"a",{get:function(){return Y(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=W(z,e);r&&delete z[e],Y(t,e,n),r&&t!==z&&Y(z,e,r)}:Y,rt=function(t,e){var n=X[t]=y(B.prototype);return U(n,{type:"Symbol",tag:t,description:e}),a||(n.description=e),n},ot=c&&"symbol"==typeof B.iterator?function(t){return"symbol"==typeof t}:function(t){return Object(t)instanceof B},it=function(t,e,n){t===z&&it($,e,n),d(t);var r=v(e,!0);return d(n),s(X,r)?(n.enumerable?(s(t,V)&&t[V][r]&&(t[V][r]=!1),n=y(n,{enumerable:g(0,!1)})):(s(t,V)||Y(t,V,g(1,{})),t[V][r]=!0),nt(t,r,n)):Y(t,r,n)},at=function(t,e){d(t);var n=h(e),r=b(n).concat(ft(n));return N(r,function(e){a&&!ct.call(n,e)||it(t,e,n[e])}),t},ct=function(t){var e=v(t,!0),n=J.call(this,e);return!(this===z&&s(X,e)&&!s($,e))&&(!(n||!s(this,e)||!s(X,e)||s(this,V)&&this[V][e])||n)},ut=function(t,e){var n=h(t),r=v(e,!0);if(n!==z||!s(X,r)||s($,r)){var o=W(n,r);return!o||!s(X,r)||s(n,V)&&n[V][r]||(o.enumerable=!0),o}},st=function(t){var e=H(h(t)),n=[];return N(e,function(t){s(X,t)||s(O,t)||n.push(t)}),n},ft=function(t){var e=t===z,n=H(e?$:h(t)),r=[];return N(n,function(t){!s(X,t)||e&&!s(z,t)||r.push(X[t])}),r};c||(j((B=function(){if(this instanceof B)throw TypeError("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,e=k(t),n=function(t){this===z&&n.call($,t),s(this,V)&&s(this[V],e)&&(this[V][e]=!1),nt(this,e,g(1,t))};return a&&et&&nt(z,e,{configurable:!0,set:n}),rt(e,t)}).prototype,"toString",function(){return C(this).tag}),M.f=ct,I.f=it,D.f=ut,m.f=x.f=st,w.f=ft,a&&(Y(B.prototype,"description",{configurable:!0,get:function(){return C(this).description}}),i||j(z,"propertyIsEnumerable",ct,{unsafe:!0})),T.f=function(t){return rt(_(t),t)}),r({global:!0,wrap:!0,forced:!c,sham:!c},{Symbol:B}),N(b(Z),function(t){R(t)}),r({target:"Symbol",stat:!0,forced:!c},{for:function(t){var e=String(t);if(s(K,e))return K[e];var n=B(e);return K[e]=n,Q[n]=e,n},keyFor:function(t){if(!ot(t))throw TypeError(t+" is not a symbol");if(s(Q,t))return Q[t]},useSetter:function(){et=!0},useSimple:function(){et=!1}}),r({target:"Object",stat:!0,forced:!c,sham:!a},{create:function(t,e){return void 0===e?y(t):at(y(t),e)},defineProperty:it,defineProperties:at,getOwnPropertyDescriptor:ut}),r({target:"Object",stat:!0,forced:!c},{getOwnPropertyNames:st,getOwnPropertySymbols:ft}),r({target:"Object",stat:!0,forced:u(function(){w.f(1)})},{getOwnPropertySymbols:function(t){return w.f(p(t))}}),q&&r({target:"JSON",stat:!0,forced:!c||u(function(){var t=B();return"[null]"!=G([t])||"{}"!=G({a:t})||"{}"!=G(Object(t))})},{stringify:function(t){for(var e,n,r=[t],o=1;arguments.length>o;)r.push(arguments[o++]);if(n=e=r[1],(l(e)||void 0!==t)&&!ot(t))return f(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!ot(e))return e}),r[1]=e,G.apply(q,r)}}),B.prototype[F]||S(B.prototype,F,B.prototype.valueOf),P(B,"Symbol"),O[V]=!0},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){n(18)("asyncIterator")},function(t,e,n){"use strict";var r=n(0),o=n(6),i=n(2),a=n(12),c=n(3),u=n(9).f,s=n(106),f=i.Symbol;if(o&&"function"==typeof f&&(!("description"in f.prototype)||void 0!==f().description)){var l={},d=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),e=this instanceof d?new f(t):void 0===t?f():f(t);return""===t&&(l[e]=!0),e};s(d,f);var p=d.prototype=f.prototype;p.constructor=d;var h=p.toString,v="Symbol(test)"==String(f("test")),g=/^Symbol\((.*)\)[^)]+$/;u(p,"description",{configurable:!0,get:function(){var t=c(this)?this.valueOf():this,e=h.call(t);if(a(l,t))return"";var n=v?e.slice(7,-1):e.replace(g,"$1");return""===n?void 0:n}}),r({global:!0,forced:!0},{Symbol:d})}},function(t,e,n){n(18)("hasInstance")},function(t,e,n){n(18)("isConcatSpreadable")},function(t,e,n){n(18)("iterator")},function(t,e,n){n(18)("match")},function(t,e,n){n(18)("matchAll")},function(t,e,n){n(18)("replace")},function(t,e,n){n(18)("search")},function(t,e,n){n(18)("species")},function(t,e,n){n(18)("split")},function(t,e,n){n(18)("toPrimitive")},function(t,e,n){n(18)("toStringTag")},function(t,e,n){n(18)("unscopables")},function(t,e,n){var r=n(0),o=n(112);r({target:"Object",stat:!0,forced:Object.assign!==o},{assign:o})},function(t,e,n){n(0)({target:"Object",stat:!0,sham:!n(6)},{create:n(35)})},function(t,e,n){var r=n(0),o=n(6);r({target:"Object",stat:!0,forced:!o,sham:!o},{defineProperty:n(9).f})},function(t,e,n){var r=n(0),o=n(6);r({target:"Object",stat:!0,forced:!o,sham:!o},{defineProperties:n(86)})},function(t,e,n){var r=n(0),o=n(113).entries;r({target:"Object",stat:!0},{entries:function(t){return o(t)}})},function(t,e,n){var r=n(0),o=n(57),i=n(1),a=n(3),c=n(42).onFreeze,u=Object.freeze;r({target:"Object",stat:!0,forced:i(function(){u(1)}),sham:!o},{freeze:function(t){return u&&a(t)?u(c(t)):t}})},function(t,e,n){var r=n(0),o=n(58),i=n(43);r({target:"Object",stat:!0},{fromEntries:function(t){var e={};return o(t,function(t,n){i(e,t,n)},void 0,!0),e}})},function(t,e,n){var r=n(0),o=n(1),i=n(19),a=n(16).f,c=n(6),u=o(function(){a(1)});r({target:"Object",stat:!0,forced:!c||u,sham:!c},{getOwnPropertyDescriptor:function(t,e){return a(i(t),e)}})},function(t,e,n){var r=n(0),o=n(6),i=n(83),a=n(19),c=n(16),u=n(43);r({target:"Object",stat:!0,sham:!o},{getOwnPropertyDescriptors:function(t){for(var e,n,r=a(t),o=c.f,s=i(r),f={},l=0;s.length>l;)void 0!==(n=o(r,e=s[l++]))&&u(f,e,n);return f}})},function(t,e,n){var r=n(0),o=n(1),i=n(110).f;r({target:"Object",stat:!0,forced:o(function(){return!Object.getOwnPropertyNames(1)})},{getOwnPropertyNames:i})},function(t,e,n){var r=n(0),o=n(1),i=n(10),a=n(28),c=n(88);r({target:"Object",stat:!0,forced:o(function(){a(1)}),sham:!c},{getPrototypeOf:function(t){return a(i(t))}})},function(t,e,n){n(0)({target:"Object",stat:!0},{is:n(115)})},function(t,e,n){var r=n(0),o=n(1),i=n(3),a=Object.isExtensible;r({target:"Object",stat:!0,forced:o(function(){a(1)})},{isExtensible:function(t){return!!i(t)&&(!a||a(t))}})},function(t,e,n){var r=n(0),o=n(1),i=n(3),a=Object.isFrozen;r({target:"Object",stat:!0,forced:o(function(){a(1)})},{isFrozen:function(t){return!i(t)||!!a&&a(t)}})},function(t,e,n){var r=n(0),o=n(1),i=n(3),a=Object.isSealed;r({target:"Object",stat:!0,forced:o(function(){a(1)})},{isSealed:function(t){return!i(t)||!!a&&a(t)}})},function(t,e,n){var r=n(0),o=n(10),i=n(55);r({target:"Object",stat:!0,forced:n(1)(function(){i(1)})},{keys:function(t){return i(o(t))}})},function(t,e,n){var r=n(0),o=n(3),i=n(42).onFreeze,a=n(57),c=n(1),u=Object.preventExtensions;r({target:"Object",stat:!0,forced:c(function(){u(1)}),sham:!a},{preventExtensions:function(t){return u&&o(t)?u(i(t)):t}})},function(t,e,n){var r=n(0),o=n(3),i=n(42).onFreeze,a=n(57),c=n(1),u=Object.seal;r({target:"Object",stat:!0,forced:c(function(){u(1)}),sham:!a},{seal:function(t){return u&&o(t)?u(i(t)):t}})},function(t,e,n){n(0)({target:"Object",stat:!0},{setPrototypeOf:n(45)})},function(t,e,n){var r=n(0),o=n(113).values;r({target:"Object",stat:!0},{values:function(t){return o(t)}})},function(t,e,n){var r=n(17),o=n(191),i=Object.prototype;o!==i.toString&&r(i,"toString",o,{unsafe:!0})},function(t,e,n){"use strict";var r=n(61),o={};o[n(7)("toStringTag")]="z",t.exports="[object z]"!==String(o)?function(){return"[object "+r(this)+"]"}:o.toString},function(t,e,n){"use strict";var r=n(0),o=n(6),i=n(66),a=n(10),c=n(21),u=n(9);o&&r({target:"Object",proto:!0,forced:i},{__defineGetter__:function(t,e){u.f(a(this),t,{get:c(e),enumerable:!0,configurable:!0})}})},function(t,e,n){"use strict";var r=n(0),o=n(6),i=n(66),a=n(10),c=n(21),u=n(9);o&&r({target:"Object",proto:!0,forced:i},{__defineSetter__:function(t,e){u.f(a(this),t,{set:c(e),enumerable:!0,configurable:!0})}})},function(t,e,n){"use strict";var r=n(0),o=n(6),i=n(66),a=n(10),c=n(26),u=n(28),s=n(16).f;o&&r({target:"Object",proto:!0,forced:i},{__lookupGetter__:function(t){var e,n=a(this),r=c(t,!0);do{if(e=s(n,r))return e.get}while(n=u(n))}})},function(t,e,n){"use strict";var r=n(0),o=n(6),i=n(66),a=n(10),c=n(26),u=n(28),s=n(16).f;o&&r({target:"Object",proto:!0,forced:i},{__lookupSetter__:function(t){var e,n=a(this),r=c(t,!0);do{if(e=s(n,r))return e.set}while(n=u(n))}})},function(t,e,n){n(0)({target:"Function",proto:!0},{bind:n(117)})},function(t,e,n){var r=n(6),o=n(9).f,i=Function.prototype,a=i.toString,c=/^\s*function ([^ (]*)/;!r||"name"in i||o(i,"name",{configurable:!0,get:function(){try{return a.call(this).match(c)[1]}catch(t){return""}}})},function(t,e,n){"use strict";var r=n(3),o=n(9),i=n(28),a=n(7)("hasInstance"),c=Function.prototype;a in c||o.f(c,a,{value:function(t){if("function"!=typeof this||!r(t))return!1;if(!r(this.prototype))return t instanceof this;for(;t=i(t);)if(this.prototype===t)return!0;return!1}})},function(t,e,n){var r=n(0),o=n(118);r({target:"Array",stat:!0,forced:!n(67)(function(t){Array.from(t)})},{from:o})},function(t,e,n){n(0)({target:"Array",stat:!0},{isArray:n(41)})},function(t,e,n){"use strict";var r=n(0),o=n(1),i=n(43);r({target:"Array",stat:!0,forced:o(function(){function t(){}return!(Array.of.call(t)instanceof t)})},{of:function(){for(var t=0,e=arguments.length,n=new("function"==typeof this?this:Array)(e);e>t;)i(n,t,arguments[t++]);return n.length=e,n}})},function(t,e,n){"use strict";var r=n(0),o=n(1),i=n(41),a=n(3),c=n(10),u=n(8),s=n(43),f=n(56),l=n(62),d=n(7)("isConcatSpreadable"),p=!o(function(){var t=[];return t[d]=!1,t.concat()[0]!==t}),h=l("concat"),v=function(t){if(!a(t))return!1;var e=t[d];return void 0!==e?!!e:i(t)};r({target:"Array",proto:!0,forced:!p||!h},{concat:function(t){var e,n,r,o,i,a=c(this),l=f(a,0),d=0;for(e=-1,r=arguments.length;e<r;e++)if(i=-1===e?a:arguments[e],v(i)){if(d+(o=u(i.length))>9007199254740991)throw TypeError("Maximum allowed index exceeded");for(n=0;n<o;n++,d++)n in i&&s(l,d,i[n])}else{if(d>=9007199254740991)throw TypeError("Maximum allowed index exceeded");s(l,d++,i)}return l.length=d,l}})},function(t,e,n){var r=n(0),o=n(119),i=n(37);r({target:"Array",proto:!0},{copyWithin:o}),i("copyWithin")},function(t,e,n){"use strict";var r=n(0),o=n(13).every;r({target:"Array",proto:!0,forced:n(29)("every")},{every:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){var r=n(0),o=n(89),i=n(37);r({target:"Array",proto:!0},{fill:o}),i("fill")},function(t,e,n){"use strict";var r=n(0),o=n(13).filter;r({target:"Array",proto:!0,forced:!n(62)("filter")},{filter:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(13).find,i=n(37),a=!0;"find"in[]&&Array(1).find(function(){a=!1}),r({target:"Array",proto:!0,forced:a},{find:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("find")},function(t,e,n){"use strict";var r=n(0),o=n(13).findIndex,i=n(37),a=!0;"findIndex"in[]&&Array(1).findIndex(function(){a=!1}),r({target:"Array",proto:!0,forced:a},{findIndex:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("findIndex")},function(t,e,n){"use strict";var r=n(0),o=n(120),i=n(10),a=n(8),c=n(24),u=n(56);r({target:"Array",proto:!0},{flat:function(){var t=arguments.length?arguments[0]:void 0,e=i(this),n=a(e.length),r=u(e,0);return r.length=o(r,e,e,n,0,void 0===t?1:c(t)),r}})},function(t,e,n){"use strict";var r=n(0),o=n(120),i=n(10),a=n(8),c=n(21),u=n(56);r({target:"Array",proto:!0},{flatMap:function(t){var e,n=i(this),r=a(n.length);return c(t),(e=u(n,0)).length=o(e,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),e}})},function(t,e,n){"use strict";var r=n(0),o=n(121);r({target:"Array",proto:!0,forced:[].forEach!=o},{forEach:o})},function(t,e,n){"use strict";var r=n(0),o=n(53).includes,i=n(37);r({target:"Array",proto:!0},{includes:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("includes")},function(t,e,n){"use strict";var r=n(0),o=n(53).indexOf,i=n(29),a=[].indexOf,c=!!a&&1/[1].indexOf(1,-0)<0,u=i("indexOf");r({target:"Array",proto:!0,forced:c||u},{indexOf:function(t){return c?a.apply(this,arguments)||0:o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(49),i=n(19),a=n(29),c=[].join,u=o!=Object,s=a("join",",");r({target:"Array",proto:!0,forced:u||s},{join:function(t){return c.call(i(this),void 0===t?",":t)}})},function(t,e,n){var r=n(0),o=n(122);r({target:"Array",proto:!0,forced:o!==[].lastIndexOf},{lastIndexOf:o})},function(t,e,n){"use strict";var r=n(0),o=n(13).map;r({target:"Array",proto:!0,forced:!n(62)("map")},{map:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(68).left;r({target:"Array",proto:!0,forced:n(29)("reduce")},{reduce:function(t){return o(this,t,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(68).right;r({target:"Array",proto:!0,forced:n(29)("reduceRight")},{reduceRight:function(t){return o(this,t,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(41),i=[].reverse,a=[1,2];r({target:"Array",proto:!0,forced:String(a)===String(a.reverse())},{reverse:function(){return o(this)&&(this.length=this.length),i.call(this)}})},function(t,e,n){"use strict";var r=n(0),o=n(3),i=n(41),a=n(34),c=n(8),u=n(19),s=n(43),f=n(62),l=n(7)("species"),d=[].slice,p=Math.max;r({target:"Array",proto:!0,forced:!f("slice")},{slice:function(t,e){var n,r,f,h=u(this),v=c(h.length),g=a(t,v),y=a(void 0===e?v:e,v);if(i(h)&&("function"!=typeof(n=h.constructor)||n!==Array&&!i(n.prototype)?o(n)&&null===(n=n[l])&&(n=void 0):n=void 0,n===Array||void 0===n))return d.call(h,g,y);for(r=new(void 0===n?Array:n)(p(y-g,0)),f=0;g<y;g++,f++)g in h&&s(r,f,h[g]);return r.length=f,r}})},function(t,e,n){"use strict";var r=n(0),o=n(13).some;r({target:"Array",proto:!0,forced:n(29)("some")},{some:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(21),i=n(10),a=n(1),c=n(29),u=[].sort,s=[1,2,3],f=a(function(){s.sort(void 0)}),l=a(function(){s.sort(null)}),d=c("sort");r({target:"Array",proto:!0,forced:f||!l||d},{sort:function(t){return void 0===t?u.call(i(this)):u.call(i(this),o(t))}})},function(t,e,n){"use strict";var r=n(0),o=n(34),i=n(24),a=n(8),c=n(10),u=n(56),s=n(43),f=n(62),l=Math.max,d=Math.min;r({target:"Array",proto:!0,forced:!f("splice")},{splice:function(t,e){var n,r,f,p,h,v,g=c(this),y=a(g.length),b=o(t,y),m=arguments.length;if(0===m?n=r=0:1===m?(n=0,r=y-b):(n=m-2,r=d(l(i(e),0),y-b)),y+n-r>9007199254740991)throw TypeError("Maximum allowed length exceeded");for(f=u(g,r),p=0;p<r;p++)(h=b+p)in g&&s(f,p,g[h]);if(f.length=r,n<r){for(p=b;p<y-r;p++)v=p+n,(h=p+r)in g?g[v]=g[h]:delete g[v];for(p=y;p>y-r+n;p--)delete g[p-1]}else if(n>r)for(p=y-r;p>b;p--)v=p+n-1,(h=p+r-1)in g?g[v]=g[h]:delete g[v];for(p=0;p<n;p++)g[p+b]=arguments[p+2];return g.length=y-r+n,f}})},function(t,e,n){n(46)("Array")},function(t,e,n){n(37)("flat")},function(t,e,n){n(37)("flatMap")},function(t,e,n){var r=n(0),o=n(34),i=String.fromCharCode,a=String.fromCodePoint;r({target:"String",stat:!0,forced:!!a&&1!=a.length},{fromCodePoint:function(t){for(var e,n=[],r=arguments.length,a=0;r>a;){if(e=+arguments[a++],o(e,1114111)!==e)throw RangeError(e+" is not a valid code point");n.push(e<65536?i(e):i(55296+((e-=65536)>>10),e%1024+56320))}return n.join("")}})},function(t,e,n){var r=n(0),o=n(19),i=n(8);r({target:"String",stat:!0},{raw:function(t){for(var e=o(t.raw),n=i(e.length),r=arguments.length,a=[],c=0;n>c;)a.push(String(e[c++])),c<r&&a.push(String(arguments[c]));return a.join("")}})},function(t,e,n){"use strict";var r=n(0),o=n(70).codeAt;r({target:"String",proto:!0},{codePointAt:function(t){return o(this,t)}})},function(t,e,n){"use strict";var r=n(0),o=n(8),i=n(92),a=n(15),c=n(94),u="".endsWith,s=Math.min;r({target:"String",proto:!0,forced:!c("endsWith")},{endsWith:function(t){var e=String(a(this));i(t);var n=arguments.length>1?arguments[1]:void 0,r=o(e.length),c=void 0===n?r:s(o(n),r),f=String(t);return u?u.call(e,f,c):e.slice(c-f.length,c)===f}})},function(t,e,n){"use strict";var r=n(0),o=n(92),i=n(15);r({target:"String",proto:!0,forced:!n(94)("includes")},{includes:function(t){return!!~String(i(this)).indexOf(o(t),arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(71),o=n(4),i=n(8),a=n(15),c=n(73),u=n(74);r("match",1,function(t,e,n){return[function(e){var n=a(this),r=null==e?void 0:e[t];return void 0!==r?r.call(e,n):new RegExp(e)[t](String(n))},function(t){var r=n(e,t,this);if(r.done)return r.value;var a=o(t),s=String(this);if(!a.global)return u(a,s);var f=a.unicode;a.lastIndex=0;for(var l,d=[],p=0;null!==(l=u(a,s));){var h=String(l[0]);d[p]=h,""===h&&(a.lastIndex=c(s,i(a.lastIndex),f)),p++}return 0===p?null:d}]})},function(t,e,n){"use strict";var r=n(0),o=n(91),i=n(15),a=n(8),c=n(21),u=n(4),s=n(61),f=n(63),l=n(14),d=n(7),p=n(30),h=n(73),v=n(20),g=n(32),y=d("matchAll"),b=v.set,m=v.getterFor("RegExp String Iterator"),x=RegExp.prototype,w=x.exec,D=o(function(t,e,n,r){b(this,{type:"RegExp String Iterator",regexp:t,string:e,global:n,unicode:r,done:!1})},"RegExp String",function(){var t=m(this);if(t.done)return{value:void 0,done:!0};var e=t.regexp,n=t.string,r=function(t,e){var n,r=t.exec;if("function"==typeof r){if("object"!=typeof(n=r.call(t,e)))throw TypeError("Incorrect exec result");return n}return w.call(t,e)}(e,n);return null===r?{value:void 0,done:t.done=!0}:t.global?(""==String(r[0])&&(e.lastIndex=h(n,a(e.lastIndex),t.unicode)),{value:r,done:!1}):(t.done=!0,{value:r,done:!1})}),I=function(t){var e,n,r,o,i,c,s=u(this),l=String(t);return e=p(s,RegExp),void 0===(n=s.flags)&&s instanceof RegExp&&!("flags"in x)&&(n=f.call(s)),r=void 0===n?"":String(n),o=new e(e===RegExp?s.source:s,r),i=!!~r.indexOf("g"),c=!!~r.indexOf("u"),o.lastIndex=a(s.lastIndex),new D(o,l,i,c)};r({target:"String",proto:!0},{matchAll:function(t){var e,n,r,o=i(this);return null!=t&&(void 0===(n=t[y])&&g&&"RegExp"==s(t)&&(n=I),null!=n)?c(n).call(t,o):(e=String(o),r=new RegExp(t,"g"),g?I.call(r,e):r[y](e))}}),g||y in x||l(x,y,I)},function(t,e,n){"use strict";var r=n(0),o=n(95).end;r({target:"String",proto:!0,forced:n(124)},{padEnd:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){"use strict";var r=n(0),o=n(95).start;r({target:"String",proto:!0,forced:n(124)},{padStart:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){n(0)({target:"String",proto:!0},{repeat:n(96)})},function(t,e,n){"use strict";var r=n(71),o=n(4),i=n(10),a=n(8),c=n(24),u=n(15),s=n(73),f=n(74),l=Math.max,d=Math.min,p=Math.floor,h=/\$([$&'`]|\d\d?|<[^>]*>)/g,v=/\$([$&'`]|\d\d?)/g;r("replace",2,function(t,e,n){return[function(n,r){var o=u(this),i=null==n?void 0:n[t];return void 0!==i?i.call(n,o,r):e.call(String(o),n,r)},function(t,i){var u=n(e,t,this,i);if(u.done)return u.value;var p=o(t),h=String(this),v="function"==typeof i;v||(i=String(i));var g=p.global;if(g){var y=p.unicode;p.lastIndex=0}for(var b=[];;){var m=f(p,h);if(null===m)break;if(b.push(m),!g)break;""===String(m[0])&&(p.lastIndex=s(h,a(p.lastIndex),y))}for(var x,w="",D=0,I=0;I<b.length;I++){m=b[I];for(var M=String(m[0]),S=l(d(c(m.index),h.length),0),j=[],E=1;E<m.length;E++)j.push(void 0===(x=m[E])?x:String(x));var A=m.groups;if(v){var O=[M].concat(j,S,h);void 0!==A&&O.push(A);var k=String(i.apply(void 0,O))}else k=r(M,h,S,j,A,i);S>=D&&(w+=h.slice(D,S)+k,D=S+M.length)}return w+h.slice(D)}];function r(t,n,r,o,a,c){var u=r+t.length,s=o.length,f=v;return void 0!==a&&(a=i(a),f=h),e.call(c,f,function(e,i){var c;switch(i.charAt(0)){case"$":return"$";case"&":return t;case"`":return n.slice(0,r);case"'":return n.slice(u);case"<":c=a[i.slice(1,-1)];break;default:var f=+i;if(0===f)return e;if(f>s){var l=p(f/10);return 0===l?e:l<=s?void 0===o[l-1]?i.charAt(1):o[l-1]+i.charAt(1):e}c=o[f-1]}return void 0===c?"":c})}})},function(t,e,n){"use strict";var r=n(71),o=n(4),i=n(15),a=n(115),c=n(74);r("search",1,function(t,e,n){return[function(e){var n=i(this),r=null==e?void 0:e[t];return void 0!==r?r.call(e,n):new RegExp(e)[t](String(n))},function(t){var r=n(e,t,this);if(r.done)return r.value;var i=o(t),u=String(this),s=i.lastIndex;a(s,0)||(i.lastIndex=0);var f=c(i,u);return a(i.lastIndex,s)||(i.lastIndex=s),null===f?-1:f.index}]})},function(t,e,n){"use strict";var r=n(71),o=n(93),i=n(4),a=n(15),c=n(30),u=n(73),s=n(8),f=n(74),l=n(72),d=n(1),p=[].push,h=Math.min,v=!d(function(){return!RegExp(4294967295,"y")});r("split",2,function(t,e,n){var r;return r="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var r=String(a(this)),i=void 0===n?4294967295:n>>>0;if(0===i)return[];if(void 0===t)return[r];if(!o(t))return e.call(r,t,i);for(var c,u,s,f=[],d=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),h=0,v=new RegExp(t.source,d+"g");(c=l.call(v,r))&&!((u=v.lastIndex)>h&&(f.push(r.slice(h,c.index)),c.length>1&&c.index<r.length&&p.apply(f,c.slice(1)),s=c[0].length,h=u,f.length>=i));)v.lastIndex===c.index&&v.lastIndex++;return h===r.length?!s&&v.test("")||f.push(""):f.push(r.slice(h)),f.length>i?f.slice(0,i):f}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:e.call(this,t,n)}:e,[function(e,n){var o=a(this),i=null==e?void 0:e[t];return void 0!==i?i.call(e,o,n):r.call(String(o),e,n)},function(t,o){var a=n(r,t,this,o,r!==e);if(a.done)return a.value;var l=i(t),d=String(this),p=c(l,RegExp),g=l.unicode,y=(l.ignoreCase?"i":"")+(l.multiline?"m":"")+(l.unicode?"u":"")+(v?"y":"g"),b=new p(v?l:"^(?:"+l.source+")",y),m=void 0===o?4294967295:o>>>0;if(0===m)return[];if(0===d.length)return null===f(b,d)?[d]:[];for(var x=0,w=0,D=[];w<d.length;){b.lastIndex=v?w:0;var I,M=f(b,v?d:d.slice(w));if(null===M||(I=h(s(b.lastIndex+(v?0:w)),d.length))===x)w=u(d,w,g);else{if(D.push(d.slice(x,w)),D.length===m)return D;for(var S=1;S<=M.length-1;S++)if(D.push(M[S]),D.length===m)return D;w=x=I}}return D.push(d.slice(x)),D}]},!v)},function(t,e,n){"use strict";var r=n(0),o=n(8),i=n(92),a=n(15),c=n(94),u="".startsWith,s=Math.min;r({target:"String",proto:!0,forced:!c("startsWith")},{startsWith:function(t){var e=String(a(this));i(t);var n=o(s(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return u?u.call(e,r,n):e.slice(n,n+r.length)===r}})},function(t,e,n){"use strict";var r=n(0),o=n(47).trim;r({target:"String",proto:!0,forced:n(97)("trim")},{trim:function(){return o(this)}})},function(t,e,n){"use strict";var r=n(0),o=n(47).start,i=n(97)("trimStart"),a=i?function(){return o(this)}:"".trimStart;r({target:"String",proto:!0,forced:i},{trimStart:a,trimLeft:a})},function(t,e,n){"use strict";var r=n(0),o=n(47).end,i=n(97)("trimEnd"),a=i?function(){return o(this)}:"".trimEnd;r({target:"String",proto:!0,forced:i},{trimEnd:a,trimRight:a})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("anchor")},{anchor:function(t){return o(this,"a","name",t)}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("big")},{big:function(){return o(this,"big","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("blink")},{blink:function(){return o(this,"blink","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("bold")},{bold:function(){return o(this,"b","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("fixed")},{fixed:function(){return o(this,"tt","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("fontcolor")},{fontcolor:function(t){return o(this,"font","color",t)}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("fontsize")},{fontsize:function(t){return o(this,"font","size",t)}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("italics")},{italics:function(){return o(this,"i","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("link")},{link:function(t){return o(this,"a","href",t)}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("small")},{small:function(){return o(this,"small","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("strike")},{strike:function(){return o(this,"strike","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("sub")},{sub:function(){return o(this,"sub","","")}})},function(t,e,n){"use strict";var r=n(0),o=n(22);r({target:"String",proto:!0,forced:n(23)("sup")},{sup:function(){return o(this,"sup","","")}})},function(t,e,n){var r=n(6),o=n(2),i=n(54),a=n(98),c=n(9).f,u=n(40).f,s=n(93),f=n(63),l=n(17),d=n(1),p=n(46),h=n(7)("match"),v=o.RegExp,g=v.prototype,y=/a/g,b=/a/g,m=new v(y)!==y;if(r&&i("RegExp",!m||d(function(){return b[h]=!1,v(y)!=y||v(b)==b||"/a/i"!=v(y,"i")}))){for(var x=function(t,e){var n=this instanceof x,r=s(t),o=void 0===e;return!n&&r&&t.constructor===x&&o?t:a(m?new v(r&&!o?t.source:t,e):v((r=t instanceof x)?t.source:t,r&&o?f.call(t):e),n?this:g,x)},w=function(t){t in x||c(x,t,{configurable:!0,get:function(){return v[t]},set:function(e){v[t]=e}})},D=u(v),I=0;D.length>I;)w(D[I++]);g.constructor=x,x.prototype=g,l(o,"RegExp",x)}p("RegExp")},function(t,e,n){"use strict";var r=n(0),o=n(72);r({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},function(t,e,n){var r=n(6),o=n(9),i=n(63);r&&"g"!=/./g.flags&&o.f(RegExp.prototype,"flags",{configurable:!0,get:i})},function(t,e,n){"use strict";var r=n(17),o=n(4),i=n(1),a=n(63),c=RegExp.prototype,u=c.toString,s=i(function(){return"/a/b"!=u.call({source:"a",flags:"b"})}),f="toString"!=u.name;(s||f)&&r(RegExp.prototype,"toString",function(){var t=o(this),e=String(t.source),n=t.flags;return"/"+e+"/"+String(void 0===n&&t instanceof RegExp&&!("flags"in c)?a.call(t):n)},{unsafe:!0})},function(t,e,n){var r=n(0),o=n(126);r({global:!0,forced:parseInt!=o},{parseInt:o})},function(t,e,n){var r=n(0),o=n(127);r({global:!0,forced:parseFloat!=o},{parseFloat:o})},function(t,e,n){"use strict";var r=n(6),o=n(2),i=n(54),a=n(17),c=n(12),u=n(25),s=n(98),f=n(26),l=n(1),d=n(35),p=n(40).f,h=n(16).f,v=n(9).f,g=n(47).trim,y=o.Number,b=y.prototype,m="Number"==u(d(b)),x=function(t){var e,n,r,o,i,a,c,u,s=f(t,!1);if("string"==typeof s&&s.length>2)if(43===(e=(s=g(s)).charCodeAt(0))||45===e){if(88===(n=s.charCodeAt(2))||120===n)return NaN}else if(48===e){switch(s.charCodeAt(1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+s}for(a=(i=s.slice(2)).length,c=0;c<a;c++)if((u=i.charCodeAt(c))<48||u>o)return NaN;return parseInt(i,r)}return+s};if(i("Number",!y(" 0o1")||!y("0b1")||y("+0x1"))){for(var w,D=function(t){var e=arguments.length<1?0:t,n=this;return n instanceof D&&(m?l(function(){b.valueOf.call(n)}):"Number"!=u(n))?s(new y(x(e)),n,D):x(e)},I=r?p(y):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),M=0;I.length>M;M++)c(y,w=I[M])&&!c(D,w)&&v(D,w,h(y,w));D.prototype=b,b.constructor=D,a(o,"Number",D)}},function(t,e,n){n(0)({target:"Number",stat:!0},{EPSILON:Math.pow(2,-52)})},function(t,e,n){n(0)({target:"Number",stat:!0},{isFinite:n(266)})},function(t,e,n){var r=n(2).isFinite;t.exports=Number.isFinite||function(t){return"number"==typeof t&&r(t)}},function(t,e,n){n(0)({target:"Number",stat:!0},{isInteger:n(128)})},function(t,e,n){n(0)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},function(t,e,n){var r=n(0),o=n(128),i=Math.abs;r({target:"Number",stat:!0},{isSafeInteger:function(t){return o(t)&&i(t)<=9007199254740991}})},function(t,e,n){n(0)({target:"Number",stat:!0},{MAX_SAFE_INTEGER:9007199254740991})},function(t,e,n){n(0)({target:"Number",stat:!0},{MIN_SAFE_INTEGER:-9007199254740991})},function(t,e,n){var r=n(0),o=n(127);r({target:"Number",stat:!0,forced:Number.parseFloat!=o},{parseFloat:o})},function(t,e,n){var r=n(0),o=n(126);r({target:"Number",stat:!0,forced:Number.parseInt!=o},{parseInt:o})},function(t,e,n){"use strict";var r=n(0),o=n(24),i=n(129),a=n(96),c=n(1),u=1..toFixed,s=Math.floor,f=function(t,e,n){return 0===e?n:e%2==1?f(t,e-1,n*t):f(t*t,e/2,n)};r({target:"Number",proto:!0,forced:u&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!c(function(){u.call({})})},{toFixed:function(t){var e,n,r,c,u=i(this),l=o(t),d=[0,0,0,0,0,0],p="",h="0",v=function(t,e){for(var n=-1,r=e;++n<6;)r+=t*d[n],d[n]=r%1e7,r=s(r/1e7)},g=function(t){for(var e=6,n=0;--e>=0;)n+=d[e],d[e]=s(n/t),n=n%t*1e7},y=function(){for(var t=6,e="";--t>=0;)if(""!==e||0===t||0!==d[t]){var n=String(d[t]);e=""===e?n:e+a.call("0",7-n.length)+n}return e};if(l<0||l>20)throw RangeError("Incorrect fraction digits");if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return String(u);if(u<0&&(p="-",u=-u),u>1e-21)if(n=(e=function(t){for(var e=0,n=t;n>=4096;)e+=12,n/=4096;for(;n>=2;)e+=1,n/=2;return e}(u*f(2,69,1))-69)<0?u*f(2,-e,1):u/f(2,e,1),n*=4503599627370496,(e=52-e)>0){for(v(0,n),r=l;r>=7;)v(1e7,0),r-=7;for(v(f(10,r,1),0),r=e-1;r>=23;)g(1<<23),r-=23;g(1<<r),v(1,1),g(2),h=y()}else v(0,n),v(1<<-e,0),h=y()+a.call("0",l);return h=l>0?p+((c=h.length)<=l?"0."+a.call("0",l-c)+h:h.slice(0,c-l)+"."+h.slice(c-l)):p+h}})},function(t,e,n){"use strict";var r=n(0),o=n(1),i=n(129),a=1..toPrecision;r({target:"Number",proto:!0,forced:o(function(){return"1"!==a.call(1,void 0)})||!o(function(){a.call({})})},{toPrecision:function(t){return void 0===t?a.call(i(this)):a.call(i(this),t)}})},function(t,e,n){var r=n(0),o=n(130),i=Math.acosh,a=Math.log,c=Math.sqrt,u=Math.LN2;r({target:"Math",stat:!0,forced:!i||710!=Math.floor(i(Number.MAX_VALUE))||i(1/0)!=1/0},{acosh:function(t){return(t=+t)<1?NaN:t>94906265.62425156?a(t)+u:o(t-1+c(t-1)*c(t+1))}})},function(t,e,n){var r=n(0),o=Math.asinh,i=Math.log,a=Math.sqrt;r({target:"Math",stat:!0,forced:!(o&&1/o(0)>0)},{asinh:function t(e){return isFinite(e=+e)&&0!=e?e<0?-t(-e):i(e+a(e*e+1)):e}})},function(t,e,n){var r=n(0),o=Math.atanh,i=Math.log;r({target:"Math",stat:!0,forced:!(o&&1/o(-0)<0)},{atanh:function(t){return 0==(t=+t)?t:i((1+t)/(1-t))/2}})},function(t,e,n){var r=n(0),o=n(99),i=Math.abs,a=Math.pow;r({target:"Math",stat:!0},{cbrt:function(t){return o(t=+t)*a(i(t),1/3)}})},function(t,e,n){var r=n(0),o=Math.floor,i=Math.log,a=Math.LOG2E;r({target:"Math",stat:!0},{clz32:function(t){return(t>>>=0)?31-o(i(t+.5)*a):32}})},function(t,e,n){var r=n(0),o=n(77),i=Math.cosh,a=Math.abs,c=Math.E;r({target:"Math",stat:!0,forced:!i||i(710)===1/0},{cosh:function(t){var e=o(a(t)-1)+1;return(e+1/(e*c*c))*(c/2)}})},function(t,e,n){var r=n(0),o=n(77);r({target:"Math",stat:!0,forced:o!=Math.expm1},{expm1:o})},function(t,e,n){n(0)({target:"Math",stat:!0},{fround:n(284)})},function(t,e,n){var r=n(99),o=Math.abs,i=Math.pow,a=i(2,-52),c=i(2,-23),u=i(2,127)*(2-c),s=i(2,-126);t.exports=Math.fround||function(t){var e,n,i=o(t),f=r(t);return i<s?f*(i/s/c+1/a-1/a)*s*c:(n=(e=(1+c/a)*i)-(e-i))>u||n!=n?f*(1/0):f*n}},function(t,e,n){var r=n(0),o=Math.abs,i=Math.sqrt;r({target:"Math",stat:!0},{hypot:function(t,e){for(var n,r,a=0,c=0,u=arguments.length,s=0;c<u;)s<(n=o(arguments[c++]))?(a=a*(r=s/n)*r+1,s=n):a+=n>0?(r=n/s)*r:n;return s===1/0?1/0:s*i(a)}})},function(t,e,n){var r=n(0),o=n(1),i=Math.imul;r({target:"Math",stat:!0,forced:o(function(){return-5!=i(4294967295,5)||2!=i.length})},{imul:function(t,e){var n=+t,r=+e,o=65535&n,i=65535&r;return 0|o*i+((65535&n>>>16)*i+o*(65535&r>>>16)<<16>>>0)}})},function(t,e,n){var r=n(0),o=Math.log,i=Math.LOG10E;r({target:"Math",stat:!0},{log10:function(t){return o(t)*i}})},function(t,e,n){n(0)({target:"Math",stat:!0},{log1p:n(130)})},function(t,e,n){var r=n(0),o=Math.log,i=Math.LN2;r({target:"Math",stat:!0},{log2:function(t){return o(t)/i}})},function(t,e,n){n(0)({target:"Math",stat:!0},{sign:n(99)})},function(t,e,n){var r=n(0),o=n(1),i=n(77),a=Math.abs,c=Math.exp,u=Math.E;r({target:"Math",stat:!0,forced:o(function(){return-2e-17!=Math.sinh(-2e-17)})},{sinh:function(t){return a(t=+t)<1?(i(t)-i(-t))/2:(c(t-1)-c(-t-1))*(u/2)}})},function(t,e,n){var r=n(0),o=n(77),i=Math.exp;r({target:"Math",stat:!0},{tanh:function(t){var e=o(t=+t),n=o(-t);return e==1/0?1:n==1/0?-1:(e-n)/(i(t)+i(-t))}})},function(t,e,n){n(27)(Math,"Math",!0)},function(t,e,n){var r=n(0),o=Math.ceil,i=Math.floor;r({target:"Math",stat:!0},{trunc:function(t){return(t>0?i:o)(t)}})},function(t,e,n){n(0)({target:"Date",stat:!0},{now:function(){return(new Date).getTime()}})},function(t,e,n){"use strict";var r=n(0),o=n(1),i=n(10),a=n(26);r({target:"Date",proto:!0,forced:o(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})})},{toJSON:function(t){var e=i(this),n=a(e);return"number"!=typeof n||isFinite(n)?e.toISOString():null}})},function(t,e,n){var r=n(0),o=n(298);r({target:"Date",proto:!0,forced:Date.prototype.toISOString!==o},{toISOString:o})},function(t,e,n){"use strict";var r=n(1),o=n(95).start,i=Math.abs,a=Date.prototype,c=a.getTime,u=a.toISOString;t.exports=r(function(){return"0385-07-25T07:06:39.999Z"!=u.call(new Date(-5e13-1))})||!r(function(){u.call(new Date(NaN))})?function(){if(!isFinite(c.call(this)))throw RangeError("Invalid time value");var t=this.getUTCFullYear(),e=this.getUTCMilliseconds(),n=t<0?"-":t>9999?"+":"";return n+o(i(t),n?6:4,0)+"-"+o(this.getUTCMonth()+1,2,0)+"-"+o(this.getUTCDate(),2,0)+"T"+o(this.getUTCHours(),2,0)+":"+o(this.getUTCMinutes(),2,0)+":"+o(this.getUTCSeconds(),2,0)+"."+o(e,3,0)+"Z"}:u},function(t,e,n){var r=n(17),o=Date.prototype,i=o.toString,a=o.getTime;new Date(NaN)+""!="Invalid Date"&&r(o,"toString",function(){var t=a.call(this);return t==t?i.call(this):"Invalid Date"})},function(t,e,n){var r=n(14),o=n(301),i=n(7)("toPrimitive"),a=Date.prototype;i in a||r(a,i,o)},function(t,e,n){"use strict";var r=n(4),o=n(26);t.exports=function(t){if("string"!==t&&"number"!==t&&"default"!==t)throw TypeError("Incorrect hint");return o(r(this),"number"!==t)}},function(t,e,n){var r=n(2);n(27)(r.JSON,"JSON",!0)},function(t,e,n){"use strict";var r,o,i,a=n(0),c=n(32),u=n(2),s=n(44),f=n(48),l=n(27),d=n(46),p=n(3),h=n(21),v=n(38),g=n(25),y=n(58),b=n(67),m=n(30),x=n(100).set,w=n(131),D=n(132),I=n(304),M=n(133),S=n(305),j=n(75),E=n(20),A=n(54),O=n(7)("species"),k="Promise",_=E.get,T=E.set,R=E.getterFor(k),P=u.Promise,L=u.TypeError,N=u.document,V=u.process,F=u.fetch,U=V&&V.versions,C=U&&U.v8||"",z=M.f,B=z,q="process"==g(V),G=!!(N&&N.createEvent&&u.dispatchEvent),W=A(k,function(){var t=P.resolve(1),e=function(){},n=(t.constructor={})[O]=function(t){t(e,e)};return!((q||"function"==typeof PromiseRejectionEvent)&&(!c||t.finally)&&t.then(e)instanceof n&&0!==C.indexOf("6.6")&&-1===j.indexOf("Chrome/66"))}),Y=W||!b(function(t){P.all(t).catch(function(){})}),H=function(t){var e;return!(!p(t)||"function"!=typeof(e=t.then))&&e},J=function(t,e,n){if(!e.notified){e.notified=!0;var r=e.reactions;w(function(){for(var o=e.value,i=1==e.state,a=0;r.length>a;){var c,u,s,f=r[a++],l=i?f.ok:f.fail,d=f.resolve,p=f.reject,h=f.domain;try{l?(i||(2===e.rejection&&Q(t,e),e.rejection=1),!0===l?c=o:(h&&h.enter(),c=l(o),h&&(h.exit(),s=!0)),c===f.promise?p(L("Promise-chain cycle")):(u=H(c))?u.call(c,d,p):d(c)):p(o)}catch(t){h&&!s&&h.exit(),p(t)}}e.reactions=[],e.notified=!1,n&&!e.rejection&&$(t,e)})}},X=function(t,e,n){var r,o;G?((r=N.createEvent("Event")).promise=e,r.reason=n,r.initEvent(t,!1,!0),u.dispatchEvent(r)):r={promise:e,reason:n},(o=u["on"+t])?o(r):"unhandledrejection"===t&&I("Unhandled promise rejection",n)},$=function(t,e){x.call(u,function(){var n,r=e.value;if(K(e)&&(n=S(function(){q?V.emit("unhandledRejection",r,t):X("unhandledrejection",t,r)}),e.rejection=q||K(e)?2:1,n.error))throw n.value})},K=function(t){return 1!==t.rejection&&!t.parent},Q=function(t,e){x.call(u,function(){q?V.emit("rejectionHandled",t):X("rejectionhandled",t,e.value)})},Z=function(t,e,n,r){return function(o){t(e,n,o,r)}},tt=function(t,e,n,r){e.done||(e.done=!0,r&&(e=r),e.value=n,e.state=2,J(t,e,!0))},et=function(t,e,n,r){if(!e.done){e.done=!0,r&&(e=r);try{if(t===n)throw L("Promise can't be resolved itself");var o=H(n);o?w(function(){var r={done:!1};try{o.call(n,Z(et,t,r,e),Z(tt,t,r,e))}catch(n){tt(t,r,n,e)}}):(e.value=n,e.state=1,J(t,e,!1))}catch(n){tt(t,{done:!1},n,e)}}};W&&(P=function(t){v(this,P,k),h(t),r.call(this);var e=_(this);try{t(Z(et,this,e),Z(tt,this,e))}catch(t){tt(this,e,t)}},(r=function(t){T(this,{type:k,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=f(P.prototype,{then:function(t,e){var n=R(this),r=z(m(this,P));return r.ok="function"!=typeof t||t,r.fail="function"==typeof e&&e,r.domain=q?V.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&J(this,n,!1),r.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new r,e=_(t);this.promise=t,this.resolve=Z(et,t,e),this.reject=Z(tt,t,e)},M.f=z=function(t){return t===P||t===i?new o(t):B(t)},c||"function"!=typeof F||a({global:!0,enumerable:!0,forced:!0},{fetch:function(t){return D(P,F.apply(u,arguments))}})),a({global:!0,wrap:!0,forced:W},{Promise:P}),l(P,k,!1,!0),d(k),i=s.Promise,a({target:k,stat:!0,forced:W},{reject:function(t){var e=z(this);return e.reject.call(void 0,t),e.promise}}),a({target:k,stat:!0,forced:c||W},{resolve:function(t){return D(c&&this===i?P:this,t)}}),a({target:k,stat:!0,forced:Y},{all:function(t){var e=this,n=z(e),r=n.resolve,o=n.reject,i=S(function(){var n=h(e.resolve),i=[],a=0,c=1;y(t,function(t){var u=a++,s=!1;i.push(void 0),c++,n.call(e,t).then(function(t){s||(s=!0,i[u]=t,--c||r(i))},o)}),--c||r(i)});return i.error&&o(i.value),n.promise},race:function(t){var e=this,n=z(e),r=n.reject,o=S(function(){var o=h(e.resolve);y(t,function(t){o.call(e,t).then(n.resolve,r)})});return o.error&&r(o.value),n.promise}})},function(t,e,n){var r=n(2);t.exports=function(t,e){var n=r.console;n&&n.error&&(1===arguments.length?n.error(t):n.error(t,e))}},function(t,e){t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},function(t,e,n){"use strict";var r=n(0),o=n(33),i=n(30),a=n(132);r({target:"Promise",proto:!0,real:!0},{finally:function(t){var e=i(this,o("Promise")),n="function"==typeof t;return this.then(n?function(n){return a(e,t()).then(function(){return n})}:t,n?function(n){return a(e,t()).then(function(){throw n})}:t)}})},function(t,e,n){"use strict";var r=n(78),o=n(134);t.exports=r("Map",function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},o,!0)},function(t,e,n){"use strict";var r=n(78),o=n(134);t.exports=r("Set",function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},o)},function(t,e,n){"use strict";var r,o=n(2),i=n(48),a=n(42),c=n(78),u=n(135),s=n(3),f=n(20).enforce,l=n(105),d=!o.ActiveXObject&&"ActiveXObject"in o,p=Object.isExtensible,h=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},v=t.exports=c("WeakMap",h,u,!0,!0);if(l&&d){r=u.getConstructor(h,"WeakMap",!0),a.REQUIRED=!0;var g=v.prototype,y=g.delete,b=g.has,m=g.get,x=g.set;i(g,{delete:function(t){if(s(t)&&!p(t)){var e=f(this);return e.frozen||(e.frozen=new r),y.call(this,t)||e.frozen.delete(t)}return y.call(this,t)},has:function(t){if(s(t)&&!p(t)){var e=f(this);return e.frozen||(e.frozen=new r),b.call(this,t)||e.frozen.has(t)}return b.call(this,t)},get:function(t){if(s(t)&&!p(t)){var e=f(this);return e.frozen||(e.frozen=new r),b.call(this,t)?m.call(this,t):e.frozen.get(t)}return m.call(this,t)},set:function(t,e){if(s(t)&&!p(t)){var n=f(this);n.frozen||(n.frozen=new r),b.call(this,t)?x.call(this,t,e):n.frozen.set(t,e)}else x.call(this,t,e);return this}})}},function(t,e,n){"use strict";n(78)("WeakSet",function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},n(135),!1,!0)},function(t,e,n){"use strict";var r=n(0),o=n(2),i=n(79),a=n(46),c=i.ArrayBuffer;r({global:!0,forced:o.ArrayBuffer!==c},{ArrayBuffer:c}),a("ArrayBuffer")},function(t,e,n){var r=n(0),o=n(5);r({target:"ArrayBuffer",stat:!0,forced:!o.NATIVE_ARRAY_BUFFER_VIEWS},{isView:o.isView})},function(t,e,n){"use strict";var r=n(0),o=n(1),i=n(79),a=n(4),c=n(34),u=n(8),s=n(30),f=i.ArrayBuffer,l=i.DataView,d=f.prototype.slice;r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:o(function(){return!new f(2).slice(1,void 0).byteLength})},{slice:function(t,e){if(void 0!==d&&void 0===e)return d.call(a(this),t);for(var n=a(this).byteLength,r=c(t,n),o=c(void 0===e?n:e,n),i=new(s(this,f))(u(o-r)),p=new l(this),h=new l(i),v=0;r<o;)h.setUint8(v++,p.getUint8(r++));return i}})},function(t,e,n){var r=n(0),o=n(79);r({global:!0,forced:!n(5).NATIVE_ARRAY_BUFFER},{DataView:o.DataView})},function(t,e,n){n(31)("Int8",1,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Uint8",1,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Uint8",1,function(t){return function(e,n,r){return t(this,e,n,r)}},!0)},function(t,e,n){n(31)("Int16",2,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Uint16",2,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Int32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Uint32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Float32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(31)("Float64",8,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){"use strict";var r=n(101),o=n(5),i=n(138);o.exportStatic("from",i,r)},function(t,e,n){"use strict";var r=n(5),o=n(101),i=r.aTypedArrayConstructor;r.exportStatic("of",function(){for(var t=0,e=arguments.length,n=new(i(this))(e);e>t;)n[t]=arguments[t++];return n},o)},function(t,e,n){"use strict";var r=n(5),o=n(119),i=r.aTypedArray;r.exportProto("copyWithin",function(t,e){return o.call(i(this),t,e,arguments.length>2?arguments[2]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(13).every,i=r.aTypedArray;r.exportProto("every",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(89),i=r.aTypedArray;r.exportProto("fill",function(t){return o.apply(i(this),arguments)})},function(t,e,n){"use strict";var r=n(5),o=n(13).filter,i=n(30),a=r.aTypedArray,c=r.aTypedArrayConstructor;r.exportProto("filter",function(t){for(var e=o(a(this),t,arguments.length>1?arguments[1]:void 0),n=i(this,this.constructor),r=0,u=e.length,s=new(c(n))(u);u>r;)s[r]=e[r++];return s})},function(t,e,n){"use strict";var r=n(5),o=n(13).find,i=r.aTypedArray;r.exportProto("find",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(13).findIndex,i=r.aTypedArray;r.exportProto("findIndex",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(13).forEach,i=r.aTypedArray;r.exportProto("forEach",function(t){o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(53).includes,i=r.aTypedArray;r.exportProto("includes",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(53).indexOf,i=r.aTypedArray;r.exportProto("indexOf",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(2),o=n(5),i=n(69),a=n(7)("iterator"),c=r.Uint8Array,u=i.values,s=i.keys,f=i.entries,l=o.aTypedArray,d=o.exportProto,p=c&&c.prototype[a],h=!!p&&("values"==p.name||null==p.name),v=function(){return u.call(l(this))};d("entries",function(){return f.call(l(this))}),d("keys",function(){return s.call(l(this))}),d("values",v,!h),d(a,v,!h)},function(t,e,n){"use strict";var r=n(5),o=r.aTypedArray,i=[].join;r.exportProto("join",function(t){return i.apply(o(this),arguments)})},function(t,e,n){"use strict";var r=n(5),o=n(122),i=r.aTypedArray;r.exportProto("lastIndexOf",function(t){return o.apply(i(this),arguments)})},function(t,e,n){"use strict";var r=n(5),o=n(13).map,i=n(30),a=r.aTypedArray,c=r.aTypedArrayConstructor;r.exportProto("map",function(t){return o(a(this),t,arguments.length>1?arguments[1]:void 0,function(t,e){return new(c(i(t,t.constructor)))(e)})})},function(t,e,n){"use strict";var r=n(5),o=n(68).left,i=r.aTypedArray;r.exportProto("reduce",function(t){return o(i(this),t,arguments.length,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=n(68).right,i=r.aTypedArray;r.exportProto("reduceRight",function(t){return o(i(this),t,arguments.length,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=r.aTypedArray,i=Math.floor;r.exportProto("reverse",function(){for(var t,e=o(this).length,n=i(e/2),r=0;r<n;)t=this[r],this[r++]=this[--e],this[e]=t;return this})},function(t,e,n){"use strict";var r=n(5),o=n(8),i=n(137),a=n(10),c=n(1),u=r.aTypedArray,s=c(function(){new Int8Array(1).set({})});r.exportProto("set",function(t){u(this);var e=i(arguments.length>1?arguments[1]:void 0,1),n=this.length,r=a(t),c=o(r.length),s=0;if(c+e>n)throw RangeError("Wrong length");for(;s<c;)this[e+s]=r[s++]},s)},function(t,e,n){"use strict";var r=n(5),o=n(30),i=n(1),a=r.aTypedArray,c=r.aTypedArrayConstructor,u=[].slice,s=i(function(){new Int8Array(1).slice()});r.exportProto("slice",function(t,e){for(var n=u.call(a(this),t,e),r=o(this,this.constructor),i=0,s=n.length,f=new(c(r))(s);s>i;)f[i]=n[i++];return f},s)},function(t,e,n){"use strict";var r=n(5),o=n(13).some,i=r.aTypedArray;r.exportProto("some",function(t){return o(i(this),t,arguments.length>1?arguments[1]:void 0)})},function(t,e,n){"use strict";var r=n(5),o=r.aTypedArray,i=[].sort;r.exportProto("sort",function(t){return i.call(o(this),t)})},function(t,e,n){"use strict";var r=n(5),o=n(8),i=n(34),a=n(30),c=r.aTypedArray;r.exportProto("subarray",function(t,e){var n=c(this),r=n.length,u=i(t,r);return new(a(n,n.constructor))(n.buffer,n.byteOffset+u*n.BYTES_PER_ELEMENT,o((void 0===e?r:i(e,r))-u))})},function(t,e,n){"use strict";var r=n(2),o=n(5),i=n(1),a=r.Int8Array,c=o.aTypedArray,u=[].toLocaleString,s=[].slice,f=!!a&&i(function(){u.call(new a(1))}),l=i(function(){return[1,2].toLocaleString()!=new a([1,2]).toLocaleString()})||!i(function(){a.prototype.toLocaleString.call([1,2])});o.exportProto("toLocaleString",function(){return u.apply(f?s.call(c(this)):c(this),arguments)},l)},function(t,e,n){"use strict";var r=n(2),o=n(5),i=n(1),a=r.Uint8Array,c=a&&a.prototype,u=[].toString,s=[].join;i(function(){u.call({})})&&(u=function(){return s.call(this)}),o.exportProto("toString",u,(c||{}).toString!=u)},function(t,e,n){var r=n(0),o=n(33),i=n(21),a=n(4),c=n(1),u=o("Reflect","apply"),s=Function.apply;r({target:"Reflect",stat:!0,forced:!c(function(){u(function(){})})},{apply:function(t,e,n){return i(t),a(n),u?u(t,e,n):s.call(t,e,n)}})},function(t,e,n){var r=n(0),o=n(33),i=n(21),a=n(4),c=n(3),u=n(35),s=n(117),f=n(1),l=o("Reflect","construct"),d=f(function(){function t(){}return!(l(function(){},[],t)instanceof t)}),p=!f(function(){l(function(){})}),h=d||p;r({target:"Reflect",stat:!0,forced:h,sham:h},{construct:function(t,e){i(t),a(e);var n=arguments.length<3?t:i(arguments[2]);if(p&&!d)return l(t,e,n);if(t==n){switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3])}var r=[null];return r.push.apply(r,e),new(s.apply(t,r))}var o=n.prototype,f=u(c(o)?o:Object.prototype),h=Function.apply.call(t,f,e);return c(h)?h:f}})},function(t,e,n){var r=n(0),o=n(6),i=n(4),a=n(26),c=n(9);r({target:"Reflect",stat:!0,forced:n(1)(function(){Reflect.defineProperty(c.f({},1,{value:1}),1,{value:2})}),sham:!o},{defineProperty:function(t,e,n){i(t);var r=a(e,!0);i(n);try{return c.f(t,r,n),!0}catch(t){return!1}}})},function(t,e,n){var r=n(0),o=n(4),i=n(16).f;r({target:"Reflect",stat:!0},{deleteProperty:function(t,e){var n=i(o(t),e);return!(n&&!n.configurable)&&delete t[e]}})},function(t,e,n){var r=n(0),o=n(3),i=n(4),a=n(12),c=n(16),u=n(28);r({target:"Reflect",stat:!0},{get:function t(e,n){var r,s,f=arguments.length<3?e:arguments[2];return i(e)===f?e[n]:(r=c.f(e,n))?a(r,"value")?r.value:void 0===r.get?void 0:r.get.call(f):o(s=u(e))?t(s,n,f):void 0}})},function(t,e,n){var r=n(0),o=n(6),i=n(4),a=n(16);r({target:"Reflect",stat:!0,sham:!o},{getOwnPropertyDescriptor:function(t,e){return a.f(i(t),e)}})},function(t,e,n){var r=n(0),o=n(4),i=n(28);r({target:"Reflect",stat:!0,sham:!n(88)},{getPrototypeOf:function(t){return i(o(t))}})},function(t,e,n){n(0)({target:"Reflect",stat:!0},{has:function(t,e){return e in t}})},function(t,e,n){var r=n(0),o=n(4),i=Object.isExtensible;r({target:"Reflect",stat:!0},{isExtensible:function(t){return o(t),!i||i(t)}})},function(t,e,n){n(0)({target:"Reflect",stat:!0},{ownKeys:n(83)})},function(t,e,n){var r=n(0),o=n(33),i=n(4);r({target:"Reflect",stat:!0,sham:!n(57)},{preventExtensions:function(t){i(t);try{var e=o("Object","preventExtensions");return e&&e(t),!0}catch(t){return!1}}})},function(t,e,n){var r=n(0),o=n(4),i=n(3),a=n(12),c=n(9),u=n(16),s=n(28),f=n(39);r({target:"Reflect",stat:!0},{set:function t(e,n,r){var l,d,p=arguments.length<4?e:arguments[3],h=u.f(o(e),n);if(!h){if(i(d=s(e)))return t(d,n,r,p);h=f(0)}if(a(h,"value")){if(!1===h.writable||!i(p))return!1;if(l=u.f(p,n)){if(l.get||l.set||!1===l.writable)return!1;l.value=r,c.f(p,n,l)}else c.f(p,n,f(0,r));return!0}return void 0!==h.set&&(h.set.call(p,r),!0)}})},function(t,e,n){var r=n(0),o=n(4),i=n(116),a=n(45);a&&r({target:"Reflect",stat:!0},{setPrototypeOf:function(t,e){o(t),i(e);try{return a(t,e),!0}catch(t){return!1}}})},function(t,e,n){n(363),n(364),n(365),n(366),n(367),n(368),n(371),n(141),t.exports=n(44)},function(t,e,n){var r=n(2),o=n(139),i=n(121),a=n(14);for(var c in o){var u=r[c],s=u&&u.prototype;if(s&&s.forEach!==i)try{a(s,"forEach",i)}catch(t){s.forEach=i}}},function(t,e,n){var r=n(2),o=n(139),i=n(69),a=n(14),c=n(7),u=c("iterator"),s=c("toStringTag"),f=i.values;for(var l in o){var d=r[l],p=d&&d.prototype;if(p){if(p[u]!==f)try{a(p,u,f)}catch(t){p[u]=f}if(p[s]||a(p,s,l),o[l])for(var h in i)if(p[h]!==i[h])try{a(p,h,i[h])}catch(t){p[h]=i[h]}}}},function(t,e,n){var r=n(2),o=n(100),i=!r.setImmediate||!r.clearImmediate;n(0)({global:!0,bind:!0,enumerable:!0,forced:i},{setImmediate:o.set,clearImmediate:o.clear})},function(t,e,n){var r=n(0),o=n(2),i=n(131),a=n(25),c=o.process,u="process"==a(c);r({global:!0,enumerable:!0,noTargetGet:!0},{queueMicrotask:function(t){var e=u&&c.domain;i(e?e.bind(t):t)}})},function(t,e,n){var r=n(0),o=n(2),i=n(75),a=[].slice,c=function(t){return function(e,n){var r=arguments.length>2,o=r?a.call(arguments,2):void 0;return t(r?function(){("function"==typeof e?e:Function(e)).apply(this,o)}:e,n)}};r({global:!0,bind:!0,forced:/MSIE .\./.test(i)},{setTimeout:c(o.setTimeout),setInterval:c(o.setInterval)})},function(t,e,n){"use strict";n(125);var r,o=n(0),i=n(6),a=n(140),c=n(2),u=n(86),s=n(17),f=n(38),l=n(12),d=n(112),p=n(118),h=n(70).codeAt,v=n(369),g=n(27),y=n(141),b=n(20),m=c.URL,x=y.URLSearchParams,w=y.getState,D=b.set,I=b.getterFor("URL"),M=Math.floor,S=Math.pow,j=/[A-Za-z]/,E=/[\d+\-.A-Za-z]/,A=/\d/,O=/^(0x|0X)/,k=/^[0-7]+$/,_=/^\d+$/,T=/^[\dA-Fa-f]+$/,R=/[\u0000\u0009\u000A\u000D #%\/:?@[\\]]/,P=/[\u0000\u0009\u000A\u000D #\/:?@[\\]]/,L=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,N=/[\u0009\u000A\u000D]/g,V=function(t,e){var n,r,o;if("["==e.charAt(0)){if("]"!=e.charAt(e.length-1))return"Invalid host";if(!(n=U(e.slice(1,-1))))return"Invalid host";t.host=n}else if(H(t)){if(e=v(e),R.test(e))return"Invalid host";if(null===(n=F(e)))return"Invalid host";t.host=n}else{if(P.test(e))return"Invalid host";for(n="",r=p(e),o=0;o<r.length;o++)n+=W(r[o],z);t.host=n}},F=function(t){var e,n,r,o,i,a,c,u=t.split(".");if(u.length&&""==u[u.length-1]&&u.pop(),(e=u.length)>4)return t;for(n=[],r=0;r<e;r++){if(""==(o=u[r]))return t;if(i=10,o.length>1&&"0"==o.charAt(0)&&(i=O.test(o)?16:8,o=o.slice(8==i?1:2)),""===o)a=0;else{if(!(10==i?_:8==i?k:T).test(o))return t;a=parseInt(o,i)}n.push(a)}for(r=0;r<e;r++)if(a=n[r],r==e-1){if(a>=S(256,5-e))return null}else if(a>255)return null;for(c=n.pop(),r=0;r<n.length;r++)c+=n[r]*S(256,3-r);return c},U=function(t){var e,n,r,o,i,a,c,u=[0,0,0,0,0,0,0,0],s=0,f=null,l=0,d=function(){return t.charAt(l)};if(":"==d()){if(":"!=t.charAt(1))return;l+=2,f=++s}for(;d();){if(8==s)return;if(":"!=d()){for(e=n=0;n<4&&T.test(d());)e=16*e+parseInt(d(),16),l++,n++;if("."==d()){if(0==n)return;if(l-=n,s>6)return;for(r=0;d();){if(o=null,r>0){if(!("."==d()&&r<4))return;l++}if(!A.test(d()))return;for(;A.test(d());){if(i=parseInt(d(),10),null===o)o=i;else{if(0==o)return;o=10*o+i}if(o>255)return;l++}u[s]=256*u[s]+o,2!=++r&&4!=r||s++}if(4!=r)return;break}if(":"==d()){if(l++,!d())return}else if(d())return;u[s++]=e}else{if(null!==f)return;l++,f=++s}}if(null!==f)for(a=s-f,s=7;0!=s&&a>0;)c=u[s],u[s--]=u[f+a-1],u[f+--a]=c;else if(8!=s)return;return u},C=function(t){var e,n,r,o;if("number"==typeof t){for(e=[],n=0;n<4;n++)e.unshift(t%256),t=M(t/256);return e.join(".")}if("object"==typeof t){for(e="",r=function(t){for(var e=null,n=1,r=null,o=0,i=0;i<8;i++)0!==t[i]?(o>n&&(e=r,n=o),r=null,o=0):(null===r&&(r=i),++o);return o>n&&(e=r,n=o),e}(t),n=0;n<8;n++)o&&0===t[n]||(o&&(o=!1),r===n?(e+=n?":":"::",o=!0):(e+=t[n].toString(16),n<7&&(e+=":")));return"["+e+"]"}return t},z={},B=d({},z,{" ":1,'"':1,"<":1,">":1,"`":1}),q=d({},B,{"#":1,"?":1,"{":1,"}":1}),G=d({},q,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),W=function(t,e){var n=h(t,0);return n>32&&n<127&&!l(e,t)?t:encodeURIComponent(t)},Y={ftp:21,file:null,gopher:70,http:80,https:443,ws:80,wss:443},H=function(t){return l(Y,t.scheme)},J=function(t){return""!=t.username||""!=t.password},X=function(t){return!t.host||t.cannotBeABaseURL||"file"==t.scheme},$=function(t,e){var n;return 2==t.length&&j.test(t.charAt(0))&&(":"==(n=t.charAt(1))||!e&&"|"==n)},K=function(t){var e;return t.length>1&&$(t.slice(0,2))&&(2==t.length||"/"===(e=t.charAt(2))||"\\"===e||"?"===e||"#"===e)},Q=function(t){var e=t.path,n=e.length;!n||"file"==t.scheme&&1==n&&$(e[0],!0)||e.pop()},Z=function(t){return"."===t||"%2e"===t.toLowerCase()},tt={},et={},nt={},rt={},ot={},it={},at={},ct={},ut={},st={},ft={},lt={},dt={},pt={},ht={},vt={},gt={},yt={},bt={},mt={},xt={},wt=function(t,e,n,o){var i,a,c,u,s,f=n||tt,d=0,h="",v=!1,g=!1,y=!1;for(n||(t.scheme="",t.username="",t.password="",t.host=null,t.port=null,t.path=[],t.query=null,t.fragment=null,t.cannotBeABaseURL=!1,e=e.replace(L,"")),e=e.replace(N,""),i=p(e);d<=i.length;){switch(a=i[d],f){case tt:if(!a||!j.test(a)){if(n)return"Invalid scheme";f=nt;continue}h+=a.toLowerCase(),f=et;break;case et:if(a&&(E.test(a)||"+"==a||"-"==a||"."==a))h+=a.toLowerCase();else{if(":"!=a){if(n)return"Invalid scheme";h="",f=nt,d=0;continue}if(n&&(H(t)!=l(Y,h)||"file"==h&&(J(t)||null!==t.port)||"file"==t.scheme&&!t.host))return;if(t.scheme=h,n)return void(H(t)&&Y[t.scheme]==t.port&&(t.port=null));h="","file"==t.scheme?f=pt:H(t)&&o&&o.scheme==t.scheme?f=rt:H(t)?f=ct:"/"==i[d+1]?(f=ot,d++):(t.cannotBeABaseURL=!0,t.path.push(""),f=bt)}break;case nt:if(!o||o.cannotBeABaseURL&&"#"!=a)return"Invalid scheme";if(o.cannotBeABaseURL&&"#"==a){t.scheme=o.scheme,t.path=o.path.slice(),t.query=o.query,t.fragment="",t.cannotBeABaseURL=!0,f=xt;break}f="file"==o.scheme?pt:it;continue;case rt:if("/"!=a||"/"!=i[d+1]){f=it;continue}f=ut,d++;break;case ot:if("/"==a){f=st;break}f=yt;continue;case it:if(t.scheme=o.scheme,a==r)t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query=o.query;else if("/"==a||"\\"==a&&H(t))f=at;else if("?"==a)t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query="",f=mt;else{if("#"!=a){t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.path.pop(),f=yt;continue}t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,t.path=o.path.slice(),t.query=o.query,t.fragment="",f=xt}break;case at:if(!H(t)||"/"!=a&&"\\"!=a){if("/"!=a){t.username=o.username,t.password=o.password,t.host=o.host,t.port=o.port,f=yt;continue}f=st}else f=ut;break;case ct:if(f=ut,"/"!=a||"/"!=h.charAt(d+1))continue;d++;break;case ut:if("/"!=a&&"\\"!=a){f=st;continue}break;case st:if("@"==a){v&&(h="%40"+h),v=!0,c=p(h);for(var b=0;b<c.length;b++){var m=c[b];if(":"!=m||y){var x=W(m,G);y?t.password+=x:t.username+=x}else y=!0}h=""}else if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&H(t)){if(v&&""==h)return"Invalid authority";d-=p(h).length+1,h="",f=ft}else h+=a;break;case ft:case lt:if(n&&"file"==t.scheme){f=vt;continue}if(":"!=a||g){if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&H(t)){if(H(t)&&""==h)return"Invalid host";if(n&&""==h&&(J(t)||null!==t.port))return;if(u=V(t,h))return u;if(h="",f=gt,n)return;continue}"["==a?g=!0:"]"==a&&(g=!1),h+=a}else{if(""==h)return"Invalid host";if(u=V(t,h))return u;if(h="",f=dt,n==lt)return}break;case dt:if(!A.test(a)){if(a==r||"/"==a||"?"==a||"#"==a||"\\"==a&&H(t)||n){if(""!=h){var w=parseInt(h,10);if(w>65535)return"Invalid port";t.port=H(t)&&w===Y[t.scheme]?null:w,h=""}if(n)return;f=gt;continue}return"Invalid port"}h+=a;break;case pt:if(t.scheme="file","/"==a||"\\"==a)f=ht;else{if(!o||"file"!=o.scheme){f=yt;continue}if(a==r)t.host=o.host,t.path=o.path.slice(),t.query=o.query;else if("?"==a)t.host=o.host,t.path=o.path.slice(),t.query="",f=mt;else{if("#"!=a){K(i.slice(d).join(""))||(t.host=o.host,t.path=o.path.slice(),Q(t)),f=yt;continue}t.host=o.host,t.path=o.path.slice(),t.query=o.query,t.fragment="",f=xt}}break;case ht:if("/"==a||"\\"==a){f=vt;break}o&&"file"==o.scheme&&!K(i.slice(d).join(""))&&($(o.path[0],!0)?t.path.push(o.path[0]):t.host=o.host),f=yt;continue;case vt:if(a==r||"/"==a||"\\"==a||"?"==a||"#"==a){if(!n&&$(h))f=yt;else if(""==h){if(t.host="",n)return;f=gt}else{if(u=V(t,h))return u;if("localhost"==t.host&&(t.host=""),n)return;h="",f=gt}continue}h+=a;break;case gt:if(H(t)){if(f=yt,"/"!=a&&"\\"!=a)continue}else if(n||"?"!=a)if(n||"#"!=a){if(a!=r&&(f=yt,"/"!=a))continue}else t.fragment="",f=xt;else t.query="",f=mt;break;case yt:if(a==r||"/"==a||"\\"==a&&H(t)||!n&&("?"==a||"#"==a)){if(".."===(s=(s=h).toLowerCase())||"%2e."===s||".%2e"===s||"%2e%2e"===s?(Q(t),"/"==a||"\\"==a&&H(t)||t.path.push("")):Z(h)?"/"==a||"\\"==a&&H(t)||t.path.push(""):("file"==t.scheme&&!t.path.length&&$(h)&&(t.host&&(t.host=""),h=h.charAt(0)+":"),t.path.push(h)),h="","file"==t.scheme&&(a==r||"?"==a||"#"==a))for(;t.path.length>1&&""===t.path[0];)t.path.shift();"?"==a?(t.query="",f=mt):"#"==a&&(t.fragment="",f=xt)}else h+=W(a,q);break;case bt:"?"==a?(t.query="",f=mt):"#"==a?(t.fragment="",f=xt):a!=r&&(t.path[0]+=W(a,z));break;case mt:n||"#"!=a?a!=r&&("'"==a&&H(t)?t.query+="%27":t.query+="#"==a?"%23":W(a,z)):(t.fragment="",f=xt);break;case xt:a!=r&&(t.fragment+=W(a,B))}d++}},Dt=function(t){var e,n,r=f(this,Dt,"URL"),o=arguments.length>1?arguments[1]:void 0,a=String(t),c=D(r,{type:"URL"});if(void 0!==o)if(o instanceof Dt)e=I(o);else if(n=wt(e={},String(o)))throw TypeError(n);if(n=wt(c,a,null,e))throw TypeError(n);var u=c.searchParams=new x,s=w(u);s.updateSearchParams(c.query),s.updateURL=function(){c.query=String(u)||null},i||(r.href=Mt.call(r),r.origin=St.call(r),r.protocol=jt.call(r),r.username=Et.call(r),r.password=At.call(r),r.host=Ot.call(r),r.hostname=kt.call(r),r.port=_t.call(r),r.pathname=Tt.call(r),r.search=Rt.call(r),r.searchParams=Pt.call(r),r.hash=Lt.call(r))},It=Dt.prototype,Mt=function(){var t=I(this),e=t.scheme,n=t.username,r=t.password,o=t.host,i=t.port,a=t.path,c=t.query,u=t.fragment,s=e+":";return null!==o?(s+="//",J(t)&&(s+=n+(r?":"+r:"")+"@"),s+=C(o),null!==i&&(s+=":"+i)):"file"==e&&(s+="//"),s+=t.cannotBeABaseURL?a[0]:a.length?"/"+a.join("/"):"",null!==c&&(s+="?"+c),null!==u&&(s+="#"+u),s},St=function(){var t=I(this),e=t.scheme,n=t.port;if("blob"==e)try{return new URL(e.path[0]).origin}catch(t){return"null"}return"file"!=e&&H(t)?e+"://"+C(t.host)+(null!==n?":"+n:""):"null"},jt=function(){return I(this).scheme+":"},Et=function(){return I(this).username},At=function(){return I(this).password},Ot=function(){var t=I(this),e=t.host,n=t.port;return null===e?"":null===n?C(e):C(e)+":"+n},kt=function(){var t=I(this).host;return null===t?"":C(t)},_t=function(){var t=I(this).port;return null===t?"":String(t)},Tt=function(){var t=I(this),e=t.path;return t.cannotBeABaseURL?e[0]:e.length?"/"+e.join("/"):""},Rt=function(){var t=I(this).query;return t?"?"+t:""},Pt=function(){return I(this).searchParams},Lt=function(){var t=I(this).fragment;return t?"#"+t:""},Nt=function(t,e){return{get:t,set:e,configurable:!0,enumerable:!0}};if(i&&u(It,{href:Nt(Mt,function(t){var e=I(this),n=String(t),r=wt(e,n);if(r)throw TypeError(r);w(e.searchParams).updateSearchParams(e.query)}),origin:Nt(St),protocol:Nt(jt,function(t){var e=I(this);wt(e,String(t)+":",tt)}),username:Nt(Et,function(t){var e=I(this),n=p(String(t));if(!X(e)){e.username="";for(var r=0;r<n.length;r++)e.username+=W(n[r],G)}}),password:Nt(At,function(t){var e=I(this),n=p(String(t));if(!X(e)){e.password="";for(var r=0;r<n.length;r++)e.password+=W(n[r],G)}}),host:Nt(Ot,function(t){var e=I(this);e.cannotBeABaseURL||wt(e,String(t),ft)}),hostname:Nt(kt,function(t){var e=I(this);e.cannotBeABaseURL||wt(e,String(t),lt)}),port:Nt(_t,function(t){var e=I(this);X(e)||(""==(t=String(t))?e.port=null:wt(e,t,dt))}),pathname:Nt(Tt,function(t){var e=I(this);e.cannotBeABaseURL||(e.path=[],wt(e,t+"",gt))}),search:Nt(Rt,function(t){var e=I(this);""==(t=String(t))?e.query=null:("?"==t.charAt(0)&&(t=t.slice(1)),e.query="",wt(e,t,mt)),w(e.searchParams).updateSearchParams(e.query)}),searchParams:Nt(Pt),hash:Nt(Lt,function(t){var e=I(this);""!=(t=String(t))?("#"==t.charAt(0)&&(t=t.slice(1)),e.fragment="",wt(e,t,xt)):e.fragment=null})}),s(It,"toJSON",function(){return Mt.call(this)},{enumerable:!0}),s(It,"toString",function(){return Mt.call(this)},{enumerable:!0}),m){var Vt=m.createObjectURL,Ft=m.revokeObjectURL;Vt&&s(Dt,"createObjectURL",function(t){return Vt.apply(m,arguments)}),Ft&&s(Dt,"revokeObjectURL",function(t){return Ft.apply(m,arguments)})}g(Dt,"URL"),o({global:!0,forced:!a,sham:!i},{URL:Dt})},function(t,e,n){"use strict";var r=/[^\0-\u007E]/,o=/[.\u3002\uFF0E\uFF61]/g,i="Overflow: input needs wider integers to process",a=Math.floor,c=String.fromCharCode,u=function(t){return t+22+75*(t<26)},s=function(t,e,n){var r=0;for(t=n?a(t/700):t>>1,t+=a(t/e);t>455;r+=36)t=a(t/35);return a(r+36*t/(t+38))},f=function(t){var e,n,r=[],o=(t=function(t){for(var e=[],n=0,r=t.length;n<r;){var o=t.charCodeAt(n++);if(o>=55296&&o<=56319&&n<r){var i=t.charCodeAt(n++);56320==(64512&i)?e.push(((1023&o)<<10)+(1023&i)+65536):(e.push(o),n--)}else e.push(o)}return e}(t)).length,f=128,l=0,d=72;for(e=0;e<t.length;e++)(n=t[e])<128&&r.push(c(n));var p=r.length,h=p;for(p&&r.push("-");h<o;){var v=2147483647;for(e=0;e<t.length;e++)(n=t[e])>=f&&n<v&&(v=n);var g=h+1;if(v-f>a((2147483647-l)/g))throw RangeError(i);for(l+=(v-f)*g,f=v,e=0;e<t.length;e++){if((n=t[e])<f&&++l>2147483647)throw RangeError(i);if(n==f){for(var y=l,b=36;;b+=36){var m=b<=d?1:b>=d+26?26:b-d;if(y<m)break;var x=y-m,w=36-m;r.push(c(u(m+x%w))),y=a(x/w)}r.push(c(u(y))),d=s(l,g,h==p),l=0,++h}}++l,++f}return r.join("")};t.exports=function(t){var e,n,i=[],a=t.toLowerCase().replace(o,".").split(".");for(e=0;e<a.length;e++)n=a[e],i.push(r.test(n)?"xn--"+f(n):n);return i.join(".")}},function(t,e,n){var r=n(4),o=n(60);t.exports=function(t){var e=o(t);if("function"!=typeof e)throw TypeError(String(t)+" is not iterable");return r(e.call(t))}},function(t,e,n){"use strict";n(0)({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return URL.prototype.toString.call(this)}})},function(t,e){!function(e){"use strict";var n,r=Object.prototype,o=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag",s="object"==typeof t,f=e.regeneratorRuntime;if(f)s&&(t.exports=f);else{(f=e.regeneratorRuntime=s?t.exports:{}).wrap=x;var l="suspendedStart",d="suspendedYield",p="executing",h="completed",v={},g={};g[a]=function(){return this};var y=Object.getPrototypeOf,b=y&&y(y(_([])));b&&b!==r&&o.call(b,a)&&(g=b);var m=M.prototype=D.prototype=Object.create(g);I.prototype=m.constructor=M,M.constructor=I,M[u]=I.displayName="GeneratorFunction",f.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===I||"GeneratorFunction"===(e.displayName||e.name))},f.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,M):(t.__proto__=M,u in t||(t[u]="GeneratorFunction")),t.prototype=Object.create(m),t},f.awrap=function(t){return{__await:t}},S(j.prototype),j.prototype[c]=function(){return this},f.AsyncIterator=j,f.async=function(t,e,n,r){var o=new j(x(t,e,n,r));return f.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},S(m),m[u]="Generator",m[a]=function(){return this},m.toString=function(){return"[object Generator]"},f.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},f.values=_,k.prototype={constructor:k,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(O),!t)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=n)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,o){return c.type="throw",c.arg=t,e.next=r,o&&(e.method="next",e.arg=n),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var u=o.call(a,"catchLoc"),s=o.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),O(n),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;O(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:_(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=n),v}}}function x(t,e,n,r){var o=e&&e.prototype instanceof D?e:D,i=Object.create(o.prototype),a=new k(r||[]);return i._invoke=function(t,e,n){var r=l;return function(o,i){if(r===p)throw new Error("Generator is already running");if(r===h){if("throw"===o)throw i;return T()}for(n.method=o,n.arg=i;;){var a=n.delegate;if(a){var c=E(a,n);if(c){if(c===v)continue;return c}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=h,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var u=w(t,e,n);if("normal"===u.type){if(r=n.done?h:d,u.arg===v)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r=h,n.method="throw",n.arg=u.arg)}}}(t,n,a),i}function w(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function D(){}function I(){}function M(){}function S(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function j(t){var e;this._invoke=function(n,r){function i(){return new Promise(function(e,i){!function e(n,r,i,a){var c=w(t[n],t,r);if("throw"!==c.type){var u=c.arg,s=u.value;return s&&"object"==typeof s&&o.call(s,"__await")?Promise.resolve(s.__await).then(function(t){e("next",t,i,a)},function(t){e("throw",t,i,a)}):Promise.resolve(s).then(function(t){u.value=t,i(u)},a)}a(c.arg)}(n,r,e,i)})}return e=e?e.then(i,i):i()}}function E(t,e){var r=t.iterator[e.method];if(r===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=n,E(t,e),"throw"===e.method))return v;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=w(r,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,v;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=n),e.delegate=null,v):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,v)}function A(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(A,this),this.reset(!0)}function _(t){if(t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(o.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=n,e.done=!0,e};return i.next=i}}return{next:T}}function T(){return{value:n,done:!0}}}(function(){return this}()||Function("return this")())},function(t,e,n){"use strict";var r=n(80),o=n(375),i=n(379),a=n(380)||0;function c(){return o(a)}t.exports=c,t.exports.generate=c,t.exports.seed=function(e){return r.seed(e),t.exports},t.exports.worker=function(e){return a=e,t.exports},t.exports.characters=function(t){return void 0!==t&&r.characters(t),r.shuffled()},t.exports.isValid=i},function(t,e,n){"use strict";var r=1;t.exports={nextValue:function(){return(r=(9301*r+49297)%233280)/233280},seed:function(t){r=t}}},function(t,e,n){"use strict";var r,o,i=n(376),a=(n(80),1459707606518);t.exports=function(t){var e="",n=Math.floor(.001*(Date.now()-a));return n===o?r++:(r=0,o=n),e+=i(6),e+=i(t),r>0&&(e+=i(r)),e+=i(n)}},function(t,e,n){"use strict";var r=n(80),o=n(377),i=n(378);t.exports=function(t){for(var e,n=0,a="";!e;)a+=i(o,r.get(),1),e=t<Math.pow(16,n+1),n++;return a}},function(t,e,n){"use strict";var r,o="object"==typeof window&&(window.crypto||window.msCrypto);r=o&&o.getRandomValues?function(t){return o.getRandomValues(new Uint8Array(t))}:function(t){for(var e=[],n=0;n<t;n++)e.push(Math.floor(256*Math.random()));return e},t.exports=r},function(t,e){t.exports=function(t,e,n){var r=(2<<Math.log(e.length-1)/Math.LN2)-1,o=Math.ceil(1.6*r*n/e.length);n=+n;for(var i="";;)for(var a=t(o),c=0;c<o;c++){var u=a[c]&r;if(e[u]&&(i+=e[u]).length===n)return i}}},function(t,e,n){"use strict";var r=n(80);t.exports=function(t){return!(!t||"string"!=typeof t||t.length<6||new RegExp("[^"+r.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(t))}},function(t,e,n){"use strict";t.exports=0},function(t,e,n){var r=n(382);"string"==typeof r&&(r=[[t.i,r,""]]),n(384)(r,{}),r.locals&&(t.exports=r.locals)},function(t,e,n){(e=t.exports=n(383)()).push([t.i,"@import url(https://fonts.googleapis.com/css?family=PT+Sans+Narrow);",""]),e.push([t.i,"@keyframes rotating{\n 0%{\n transform: rotate(45deg);\n }\n 50%{\n transform: rotate(90deg);\n }\n}\n.default .ruler-row:hover .painted{\n background: white;\n}\n.default .mark{\n background: rgba(255, 90, 0, 1);\n}\n.default .empty{\n background: white;\n}\n.default .painted{\n background: rgba(255, 90, 0, .24);\n}\n.default .line{\n border: 1px solid #9e9e9e;\n}\n.default .tooltiptext{\n background-color: rgb(44, 91, 134);\n}\n.blue .ruler-row:hover .painted{\n background: white;\n}\n.blue .mark{\n background: #448AFF;\n}\n.blue .empty{\n background: white;\n}\n.blue .painted{\n background: rgba(189, 189, 189, .46);\n}\n.blue .line{\n border: 1px solid #9e9e9e;\n}\n.blue .tooltiptext{\n background-color: rgb(44, 91, 134);\n}\n.grey .ruler-row:hover .painted{\n background: white;\n}\n.grey .mark{\n background: #9E9E9E;\n}\n.grey .empty{\n background: white;\n}\n.grey .painted{\n background: rgba(189, 189, 189, .46);\n}\n.grey .line{\n border: 1px solid #9e9e9e;\n}\n.grey .tooltiptext{\n background-color: rgb(44, 91, 134);\n}\n.white .ruler-row:hover .painted{\n background: white;\n}\n.white .mark{\n background: rgba(172, 148, 179, .49);\n}\n.white .empty{\n background: white;\n}\n.white .painted{\n background: #FFFFFF;\n}\n.white .line{\n border: 1px solid #9e9e9e;\n}\n.white .tooltiptext{\n background-color: rgb(44, 91, 134);\n}\n\n.ruler-container {\n position: relative;\n display: block;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n margin: 40px auto;\n}\n\n.ruler-container .y-axis-wrapper {\n display: inline-block;\n position: relative;\n bottom: 29px;\n}\n\n.ruler-container .y-axis-wrapper .y-axis {\n display: inline-block;\n padding: 0 10px;\n color: #9e9e9e;\n font-family: 'PT Sans Narrow',sans-serif;\n border-right: 1px solid rgba(172, 148, 179, .49);\n}\n\n.ruler-container .y-axis-wrapper .y-axis .y-caption {\n height: 20px;\n float: right;\n clear: both;\n}\n\n.ruler-container .marks-wrapper {\n overflow: hidden;\n display: inline-block;\n width: auto;\n max-width: 90vw;\n height: 230px;\n}\n\n.ruler-container .marks-wrapper .x-axis {\n font-family: 'PT Sans Narrow',sans-serif;\n color: #9e9e9e;\n max-height: 30px;\n border-top: 1px solid rgba(172, 148, 179, .49);\n}\n\n.ruler-container .marks-wrapper .x-axis .x-caption {\n display: inline-block;\n max-height: 30px;\n margin: 5px 0px;\n text-align: center;\n color: #9e9e9e;\n}\n\n.ruler-container .marks-wrapper .marks {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: row;\n flex-direction: row;\n height: 200px;\n border-bottom: 1px solid rgba(172, 148, 179, .49);\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: column-reverse;\n flex-direction: column-reverse;\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark {\n position: relative;\n border-top: 1px solid rgba(249, 250, 249, .9);\n border-left: 1px solid rgba(249, 250, 249, .9);\n box-sizing: border-box;\n -ms-flex: 0 0 auto;\n flex: 0 0 auto;\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark .line {\n position: relative;\n z-index: 99;\n box-sizing: border-box;\n transform-origin: left center\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark .line:hover + .tooltiptext{\n visibility: hidden;\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark:hover{\n cursor: pointer;\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark:hover .tooltiptext{\n visibility: visible;\n}\n\n.ruler-container .marks-wrapper .marks .ruler-row .mark.white{\n background: white;\n}\n\n.tooltiptext {\n position: absolute;\n z-index: 9999999;\n visibility: hidden;\n width: 130px;\n left: 20px;\n color: #ffffff;\n padding: 5px 5px;\n font-family: 'PT Sans Narrow',sans-serif;\n}\n\n.tooltiptext div {\n word-wrap: break-word;\n text-align: center\n}\n\n.tooltiptext div.date{\n margin: 10px 0 5px;\n font-weight: bold;\n}\n\n.tooltiptext div.value{\n margin: 5px 0 5px;\n font-size: 18px;\n font-weight: bold;\n}\n",""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<e.length;o++){var a=e[o];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),t.push(a))}},t}},function(t,e){var n={},r=function(t){var e;return function(){return void 0===e&&(e=t.apply(this,arguments)),e}},o=r(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())}),i=r(function(){return document.head||document.getElementsByTagName("head")[0]}),a=null,c=0,u=[];function s(t,e){for(var r=0;r<t.length;r++){var o=t[r],i=n[o.id];if(i){i.refs++;for(var a=0;a<i.parts.length;a++)i.parts[a](o.parts[a]);for(;a<o.parts.length;a++)i.parts.push(h(o.parts[a],e))}else{var c=[];for(a=0;a<o.parts.length;a++)c.push(h(o.parts[a],e));n[o.id]={id:o.id,refs:1,parts:c}}}}function f(t){for(var e=[],n={},r=0;r<t.length;r++){var o=t[r],i=o[0],a={css:o[1],media:o[2],sourceMap:o[3]};n[i]?n[i].parts.push(a):e.push(n[i]={id:i,parts:[a]})}return e}function l(t,e){var n=i(),r=u[u.length-1];if("top"===t.insertAt)r?r.nextSibling?n.insertBefore(e,r.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),u.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function d(t){t.parentNode.removeChild(t);var e=u.indexOf(t);e>=0&&u.splice(e,1)}function p(t){var e=document.createElement("style");return e.type="text/css",l(t,e),e}function h(t,e){var n,r,o;if(e.singleton){var i=c++;n=a||(a=p(e)),r=y.bind(null,n,i,!1),o=y.bind(null,n,i,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=function(t){var e=document.createElement("link");return e.rel="stylesheet",l(t,e),e}(e),r=function(t,e){var n=e.css,r=e.sourceMap;r&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([n],{type:"text/css"}),i=t.href;t.href=URL.createObjectURL(o),i&&URL.revokeObjectURL(i)}.bind(null,n),o=function(){d(n),n.href&&URL.revokeObjectURL(n.href)}):(n=p(e),r=function(t,e){var n=e.css,r=e.media;if(r&&t.setAttribute("media",r),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,n),o=function(){d(n)});return r(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;r(t=e)}else o()}}t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");void 0===(e=e||{}).singleton&&(e.singleton=o()),void 0===e.insertAt&&(e.insertAt="bottom");var r=f(t);return s(r,e),function(t){for(var o=[],i=0;i<r.length;i++){var a=r[i];(c=n[a.id]).refs--,o.push(c)}for(t&&s(f(t),e),i=0;i<o.length;i++){var c;if(0===(c=o[i]).refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete n[c.id]}}}};var v,g=(v=[],function(t,e){return v[t]=e,v.filter(Boolean).join("\n")});function y(t,e,n,r){var o=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=g(e,o);else{var i=document.createTextNode(o),a=t.childNodes;a[e]&&t.removeChild(a[e]),a.length?t.insertBefore(i,a[e]):t.appendChild(i)}}}]))}}); //# sourceMappingURL=app.js.map
img/portfolio/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
jdaly04/portfolio
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/parser/paladin/retribution/modules/core/Retribution.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatNumber, formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import { ABILITIES_AFFECTED_BY_DAMAGE_INCREASES } from '../../constants'; const RETRIBUTION_DAMAGE_BONUS = 0.2; class Retribution extends Analyzer { bonusDmg = 0; abilitiesAffectedByRetribution = ABILITIES_AFFECTED_BY_DAMAGE_INCREASES.slice(); constructor(...args) { super(...args); this.abilitiesAffectedByRetribution.push(SPELLS.MELEE); // event listeners this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(ABILITIES_AFFECTED_BY_DAMAGE_INCREASES), this.onAffectedDamage); this.addEventListener(Events.fightend, this.onFightEnd); } onAffectedDamage(event) { if (this.selectedCombatant.hasBuff(SPELLS.RETRIBUTION_BUFF.id)) { this.bonusDmg += calculateEffectiveDamage(event, RETRIBUTION_DAMAGE_BONUS); } } onFightEnd() { this.active = this.bonusDmg > 0; } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.UNIMPORTANT()} icon={<SpellIcon id={SPELLS.RETRIBUTION_BUFF.id} />} value={`${formatNumber(this.bonusDmg / this.owner.fightDuration * 1000)} DPS`} label="Damage Contributed" tooltip={`Retribution contributed ${formatNumber(this.bonusDmg)} total damage (${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDmg))} %).`} /> ); } } export default Retribution;
admin/client/components/AudioSelector.js
nickhsine/keystone
'use strict'; import { parseAudioAPIResponse, parseImageAPIResponse } from '../../../lib/parseAPIResponse'; import { Button, Modal, Pagination } from 'elemental'; import qs from 'qs'; import xhr from 'xhr'; import AudioSelection from './AudioSelection'; import SelectorMixin from './mixins/SelectorMixin'; import React from 'react'; // lodash import forEach from 'lodash/forEach' import get from 'lodash/get'; import merge from 'lodash/merge'; import set from 'lodash/set'; const _ = { forEach, get, merge, set, } const PAGINATION_LIMIT = 10; class AudioSelector extends SelectorMixin(React.Component) { constructor (props) { super(props); this.state.selectedItems = props.selectedAudios; } componentWillReceiveProps (nextProps) { let props = {}; _.merge(props, nextProps, { selectedItems: nextProps.selectedAudios }); super.componentWillReceiveProps(props); } _loadImage (imageId) { return new Promise((resolve, reject) => { if (!imageId) { return reject(new Error('Should provide imageId')); } xhr({ url: Keystone.adminPath + this.API + 'images/' + imageId, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading item:', err); return reject(err); } resolve(parseImageAPIResponse(data)); }); }); } _loadCoverPhotoForAudio (audio) { return new Promise((resolve, reject) => { let imageId = _.get(audio, ['fields', 'coverPhoto']); this._loadImage(imageId) .then((image) => { _.set(audio, ['fields', 'coverPhoto'], image); resolve(parseAudioAPIResponse(audio)); }, (err) => { resolve(parseAudioAPIResponse(audio)); }); }); } _loadCoverPhotoForAudios (audios) { return new Promise((resolve, reject) => { let promises = []; _.forEach(audios, (audio) => { promises.push(this._loadCoverPhotoForAudio(audio)); }); Promise.all(promises) .then((audios) => { resolve(audios); }, (err) => { reject(err); }); }); } loadItems (querystring = '') { return new Promise((resolve, reject) => { super.loadItems(querystring) .then((audios) => { this._loadCoverPhotoForAudios(audios) .then((audios) => { resolve(audios); }); }).catch((err) => reject(err)); }); } /** build query string filtered by title for keystone api * @override * @param {string[]} [filters=[]] - keywords for filtering * @param {number} [page=0] - Page we used to calculate how many items we want to skip * @param {limit} [limit=10] - The number of items we want to get * @return {string} a query string */ _buildFilters (filters = [], page = 0, limit = 10) { let filterQuery = { title: { value: filters, }, }; let queryString = { filters: JSON.stringify(filterQuery), select: 'audio,description,title,coverPhoto', limit: limit, skip: page === 0 ? 0 : (page - 1) * limit, }; return qs.stringify(queryString); } render () { if (this.state.error) { return ( <span>There is an error, please reload the page.{this.state.error}</span> ); } const { isSelectionOpen, items, selectedItems } = this.state; return ( <Modal isOpen={isSelectionOpen} onCancel={this.handleCancel} width="large" backdropClosesModal> <Modal.Header text="Select Audio" showCloseButton onClose={this.handleCancel} /> <Modal.Body> <div> {this._renderSearchFilter()} <AudioSelection audios={items} selectedAudios={selectedItems} selectionLimit={this.props.selectionLimit} updateSelection={this.updateSelection} /> <Pagination currentPage={this.state.currentPage} onPageSelect={this.handlePageSelect} pageSize={this.PAGE_SIZE} total={this.state.total} limit={PAGINATION_LIMIT} /> </div> </Modal.Body> <Modal.Footer> <Button type="primary" onClick={this.handleSave}>Save</Button> <Button type="link-cancel" onClick={this.handleCancel}>Cancel</Button> </Modal.Footer> </Modal> ); } } AudioSelector.propTypes = { apiPath: React.PropTypes.string, isSelectionOpen: React.PropTypes.bool, onChange: React.PropTypes.func.isRequired, onFinish: React.PropTypes.func.isRequired, selectedAudios: React.PropTypes.array, selectionLimit: React.PropTypes.number, }; AudioSelector.defaultProps = { apiPath: '', isSelectionOpen: false, selectedAudios: [], selectionLimit: 1, }; export default AudioSelector;
ajax/libs/rxjs/2.3.8/rx.all.js
viskin/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 = 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; }; // 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 = { done: true, value: undefined }; /** `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; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } 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; 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; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ 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)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (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) { if (index === undefined) { 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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * 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 BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; 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) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } 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; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * 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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; 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 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 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) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { 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); } 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 scheduleMethod, clearMethod = noop; (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 setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * 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 = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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, 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 (exception) { var notification = new Notification('E'); notification.exception = exception; 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 enumerableFor = Enumerable.forEach = 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. * * @param observer Observer object. * @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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(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.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @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. * * @memberOf AbstractObserver * @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 (exception) { this._onError(exception); }; /** * 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; 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 (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); 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. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return 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)); }); }; /** * 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; }); }; /** * 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 new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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 Error('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; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * 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. */ 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 = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = 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(); } }); }); }; /** * 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 (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * 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); }; /** * 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; }); }; /** * 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 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @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 = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @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(); if (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 = argsOrArray(arguments, 0); 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 (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.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. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).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. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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 if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * 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 = argsOrArray(arguments, 0); 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), function () { self(); }, function () { 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 (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 if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * 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 (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. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @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) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.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) { try { if (!hasValue) { hasValue = true; } 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 () { if (!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); if (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. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @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(); }); }); }; /** * 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 (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * 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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? 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; 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(); }); }).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; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // 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 (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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 (exception) { observer.onError(exception); 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} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * 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(); }); }).mergeAll(); }; /** * 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 observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.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; } } if (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 Error(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) { remaining--; observer.onNext(x); if (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. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(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 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 (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; function toSet(source, type) { return new AnonymousObservable(function (observer) { var s = new type(); return source.subscribe( s.add.bind(s), observer.onError.bind(observer), function () { observer.onNext(s); observer.onCompleted(); }); }); } if (!!root.Set) { /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { return toSet(this, root.Set); }; } if (!!root.WeakSet) { /** * Converts the observable sequence to a WeakSet if it exists. * @returns {Observable} An observable sequence with a single value of a WeakSet containing the values from the observable sequence. */ observableProto.toSet = function () { return toSet(this, root.WeakSet); }; } function toMap(source, type, keySelector, elementSelector) { return new AnonymousObservable(function (observer) { var m = new type(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { observer.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { observer.onError(e); return; } } m.set(key, element); }, observer.onError.bind(observer), function () { observer.onNext(m); observer.onCompleted(); }); }); } if (!!root.Map) { /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { return toMap(this, root.Map, keySelector, elementSelector); }; } if (!!root.WeakMap) { /** * Converts the observable sequence to a WeakMap if it exists. * @param {Function} keySelector A function which produces the key for the WeakMap * @param {Function} [elementSelector] An optional function which produces the element for the WeakMap. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a WeakMap containing the values from the observable sequence. */ observableProto.toWeakMap = function (keySelector, elementSelector) { return toMap(this, root.WeakMap, keySelector, elementSelector); }; } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * 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); }); }; }; /** * 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); }); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } 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(); }; /** * 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); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } previousShouldFire = results.shouldFire; }, 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(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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)); /** * 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 ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * 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(null).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 ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * 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 ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * 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(); }; /** @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 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) { 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 (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 = []; } }, /** * 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) { this.value = value; 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; 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 RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(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; }, /* @private */ _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) { var observer; checkDisposed.call(this); if (!this.isStopped) { 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++) { 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) { var observer; checkDisposed.call(this); if (!this.isStopped) { 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++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { 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++) { 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)); 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)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch(exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; 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. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @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 (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { 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); return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; isSpan && (nextSpan += timeShift); isShift && (nextShift += timeShift); m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); } }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s = new Subject() timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * 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. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @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 || (other = observableThrow(new Error('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); var createTimer = function () { 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); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @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). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); 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 GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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 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 = []; } }, /** * 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) { 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)); 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));
resource/js/components/Page/PagePath.js
crow-misia/crowi
import React from 'react'; export default class PagePath extends React.Component { // Original Crowi.linkPath /* Crowi.linkPath = function(revisionPath) { var $revisionPath = revisionPath || '#revision-path'; var $title = $($revisionPath); var pathData = $('#content-main').data('path'); if (!pathData) { return ; } var realPath = pathData.trim(); if (realPath.substr(-1, 1) == '/') { realPath = realPath.substr(0, realPath.length - 1); } var path = ''; var pathHtml = ''; var splittedPath = realPath.split(/\//); splittedPath.shift(); splittedPath.forEach(function(sub) { path += '/'; pathHtml += ' <a href="' + path + '">/</a> '; if (sub) { path += sub; pathHtml += '<a href="' + path + '">' + sub + '</a>'; } }); if (path.substr(-1, 1) != '/') { path += '/'; pathHtml += ' <a href="' + path + '" class="last-path">/</a>'; } $title.html(pathHtml); }; */ linkPath(path) { return path; } render() { const page = this.props.page; const shortPath = this.getShortPath(page.path); const pathPrefix = page.path.replace(new RegExp(shortPath + '(/)?$'), ''); return ( <span className="page-path"> {pathPrefix}<strong>{shortPath}</strong> </span> ); } } PagePath.propTypes = { page: React.PropTypes.object.isRequired, }; PagePath.defaultProps = { page: {}, };
blueocean-material-icons/src/js/components/svg-icons/navigation-arrow-drop-right.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../SvgIcon'; const NavigationArrowDropRight = (props) => ( <SvgIcon {...props}> <path d="M9.5,7l5,5l-5,5V7z" /> </SvgIcon> ); NavigationArrowDropRight.displayName = 'NavigationArrowDropRight'; NavigationArrowDropRight.muiName = 'SvgIcon'; export default NavigationArrowDropRight;
src/Input/ThemedInputErrorSuffix.js
skyiea/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import InputErrorSuffix from './InputErrorSuffix'; import Tooltip from '../Tooltip'; import Error from '../Icons/dist/components/Error'; import styles from './Input.scss'; const placementToMoveBy = { right: {x: 2, y: -10}, left: {x: -2, y: -10}, top: {x: 0, y: -10}, bottom: {x: 0, y: -8} }; const AmaterialErrorSuffix = ({focused, error, errorMessage, placement, onShow}) => focused ? null : <Tooltip dataHook="input-tooltip" disabled={!error && !errorMessage} placement={placement} maxWidth="230px" hideDelay={5} showDelay={5} active={focused} moveBy={placementToMoveBy[placement]} alignment="center" content={errorMessage} overlay="" textAlign="left" onShow={onShow} > <div className={classNames(styles.errorIcon, styles.suffix)}><Error size="1.5em"/></div> </Tooltip>; AmaterialErrorSuffix.propTypes = { errorMessage: PropTypes.node.isRequired, error: PropTypes.bool, focused: PropTypes.bool, placement: PropTypes.oneOf(['left', 'right', 'top', 'bottom']), onShow: PropTypes.func }; AmaterialErrorSuffix.defaultProps = { placement: 'right' }; class ThemedInputErrorSuffix extends InputErrorSuffix { render() { const {theme, focused, error, errorMessage, tooltipPlacement, onTooltipShow} = this.props; return theme === 'amaterial' ? <AmaterialErrorSuffix focused={focused} error={error} errorMessage={errorMessage} placement={tooltipPlacement} onShow={onTooltipShow}/> : super.render(); } } ThemedInputErrorSuffix.propTypes = { tooltipPlacement: PropTypes.oneOf(['left', 'right', 'top', 'bottom']), onTooltipShow: PropTypes.func }; export default ThemedInputErrorSuffix;
ajax/libs/dexie/1.5.0-rc.3/dexie.es6.js
joeyparrish/cdnjs
/* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.0-rc.3, Thu Oct 13 2016 * www.dexie.com * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var keys = Object.keys; var isArray = Array.isArray; var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; function extend(obj, extension) { if (typeof extension !== 'object') return obj; keys(extension).forEach(function (key) { obj[key] = extension[key]; }); return obj; } const getProto = Object.getPrototypeOf; const _hasOwn = {}.hasOwnProperty; function hasOwn(obj, prop) { return _hasOwn.call(obj, prop); } function props (proto, extension) { if (typeof extension === 'function') extension = extension(getProto(proto)); keys(extension).forEach(key => { setProp(proto, key, extension[key]); }); } function setProp(obj, prop, functionOrGetSet, options) { Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} : {value: functionOrGetSet, configurable: true, writable: true}, options)); } function derive(Child) { return { from: function (Parent) { Child.prototype = Object.create(Parent.prototype); setProp(Child.prototype, "constructor", Child); return { extend: props.bind(null, Child.prototype) }; } }; } const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; function getPropertyDescriptor(obj, prop) { var pd = getOwnPropertyDescriptor(obj, prop), proto; return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop); } var _slice = [].slice; function slice(args, start, end) { return _slice.call(args, start, end); } function override(origFunc, overridedFactory) { return overridedFactory(origFunc); } function doFakeAutoComplete(fn) { var to = setTimeout(fn, 1000); clearTimeout(to); } function assert (b) { if (!b) throw new Error("Assertion Failed"); } function asap(fn) { if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0); } /** Generate an object (hash map) based on given array. * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to * instert on the resulting object for each item in the array. If this function returns a falsy value, the * current item wont affect the resulting object. */ function arrayToObject (array, extractor) { return array.reduce((result, item, i) => { var nameAndValue = extractor(item, i); if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; return result; }, {}); } function trycatcher(fn, reject) { return function () { try { fn.apply(this, arguments); } catch (e) { reject(e); } }; } function tryCatch(fn, onerror, args) { try { fn.apply(null, args); } catch (ex) { onerror && onerror(ex); } } function getByKeyPath(obj, keyPath) { // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. if (!keyPath) return obj; if (typeof keyPath !== 'string') { var rv = []; for (var i = 0, l = keyPath.length; i < l; ++i) { var val = getByKeyPath(obj, keyPath[i]); rv.push(val); } return rv; } var period = keyPath.indexOf('.'); if (period !== -1) { var innerObj = obj[keyPath.substr(0, period)]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); } return undefined; } function setByKeyPath(obj, keyPath, value) { if (!obj || keyPath === undefined) return; if ('isFrozen' in Object && Object.isFrozen(obj)) return; if (typeof keyPath !== 'string' && 'length' in keyPath) { assert(typeof value !== 'string' && 'length' in value); for (var i = 0, l = keyPath.length; i < l; ++i) { setByKeyPath(obj, keyPath[i], value[i]); } } else { var period = keyPath.indexOf('.'); if (period !== -1) { var currentKeyPath = keyPath.substr(0, period); var remainingKeyPath = keyPath.substr(period + 1); if (remainingKeyPath === "") if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value; else { var innerObj = obj[currentKeyPath]; if (!innerObj) innerObj = (obj[currentKeyPath] = {}); setByKeyPath(innerObj, remainingKeyPath, value); } } else { if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value; } } } function delByKeyPath(obj, keyPath) { if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined); else if ('length' in keyPath) [].map.call(keyPath, function(kp) { setByKeyPath(obj, kp, undefined); }); } function shallowClone(obj) { var rv = {}; for (var m in obj) { if (hasOwn(obj, m)) rv[m] = obj[m]; } return rv; } function deepClone(any) { if (!any || typeof any !== 'object') return any; var rv; if (isArray(any)) { rv = []; for (var i = 0, l = any.length; i < l; ++i) { rv.push(deepClone(any[i])); } } else if (any instanceof Date) { rv = new Date(); rv.setTime(any.getTime()); } else { rv = any.constructor ? Object.create(any.constructor.prototype) : {}; for (var prop in any) { if (hasOwn(any, prop)) { rv[prop] = deepClone(any[prop]); } } } return rv; } function getObjectDiff(a, b, rv, prfx) { // Compares objects a and b and produces a diff object. rv = rv || {}; prfx = prfx || ''; keys(a).forEach(prop => { if (!hasOwn(b, prop)) rv[prfx+prop] = undefined; // Property removed else { var ap = a[prop], bp = b[prop]; if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor) // Same type of object but its properties may have changed getObjectDiff (ap, bp, rv, prfx + prop + "."); else if (ap !== bp) rv[prfx + prop] = b[prop];// Primitive value changed } }); keys(b).forEach(prop => { if (!hasOwn(a, prop)) { rv[prfx+prop] = b[prop]; // Property added } }); return rv; } // If first argument is iterable or array-like, return it as an array const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; const getIteratorOf = iteratorSymbol ? function(x) { var i; return x != null && (i = x[iteratorSymbol]) && i.apply(x); } : function () { return null; }; const NO_CHAR_ARRAY = {}; // Takes one or several arguments and returns an array based on the following criteras: // * If several arguments provided, return arguments converted to an array in a way that // still allows javascript engine to optimize the code. // * If single argument is an array, return a clone of it. // * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special // case to the two bullets below. // * If single argument is an iterable, convert it to an array and return the resulting array. // * If single argument is array-like (has length of type number), convert it to an array. function getArrayOf (arrayLike) { var i, a, x, it; if (arguments.length === 1) { if (isArray(arrayLike)) return arrayLike.slice(); if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; if ((it = getIteratorOf(arrayLike))) { a = []; while ((x = it.next()), !x.done) a.push(x.value); return a; } if (arrayLike == null) return [arrayLike]; i = arrayLike.length; if (typeof i === 'number') { a = new Array(i); while (i--) a[i] = arrayLike[i]; return a; } return [arrayLike]; } i = arguments.length; a = new Array(i); while (i--) a[i] = arguments[i]; return a; } const concat = [].concat; function flatten (a) { return concat.apply([], a); } function nop() { } function mirror(val) { return val; } function pureFunctionChain(f1, f2) { // Enables chained events that takes ONE argument and returns it to the next function in chain. // This pattern is used in the hook("reading") event. if (f1 == null || f1 === mirror) return f2; return function (val) { return f2(f1(val)); }; } function callBoth(on1, on2) { return function () { on1.apply(this, arguments); on2.apply(this, arguments); }; } function hookCreatingChain(f1, f2) { // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. // This pattern is used in the hook("creating") event. if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res !== undefined) arguments[0] = res; var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res2 !== undefined ? res2 : res; }; } function hookDeletingChain(f1, f2) { if (f1 === nop) return f2; return function () { f1.apply(this, arguments); var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = this.onerror = null; f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; }; } function hookUpdatingChain(f1, f2) { if (f1 === nop) return f2; return function (modifications) { var res = f1.apply(this, arguments); extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res === undefined ? (res2 === undefined ? undefined : res2) : (extend(res, res2)); }; } function reverseStoppableEventChain(f1, f2) { if (f1 === nop) return f2; return function () { if (f2.apply(this, arguments) === false) return false; return f1.apply(this, arguments); }; } function promisableChain(f1, f2) { if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res && typeof res.then === 'function') { var thiz = this, i = arguments.length, args = new Array(i); while (i--) args[i] = arguments[i]; return res.then(function () { return f2.apply(thiz, args); }); } return f2.apply(this, arguments); }; } // By default, debug will be true only if platform is a web platform and its page is served from localhost. // When debug = true, error's stacks will contain asyncronic long stacks. var debug = typeof location !== 'undefined' && // By default, use debug mode if served from localhost. /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); function setDebug(value, filter) { debug = value; libraryFilter = filter; } var libraryFilter = () => true; const NEEDS_THROW_FOR_STACK = !new Error("").stack; function getErrorWithStack() { "use strict"; if (NEEDS_THROW_FOR_STACK) try { // Doing something naughty in strict mode here to trigger a specific error // that can be explicitely ignored in debugger's exception settings. // If we'd just throw new Error() here, IE's debugger's exception settings // will just consider it as "exception thrown by javascript code" which is // something you wouldn't want it to ignore. getErrorWithStack.arguments; throw new Error(); // Fallback if above line don't throw. } catch(e) { return e; } return new Error(); } function prettyStack(exception, numIgnoredFrames) { var stack = exception.stack; if (!stack) return ""; numIgnoredFrames = (numIgnoredFrames || 0); if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length; return stack.split('\n') .slice(numIgnoredFrames) .filter(libraryFilter) .map(frame => "\n" + frame) .join(''); } function deprecated (what, fn) { return function () { console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`); return fn.apply(this, arguments); } } var dexieErrorNames = [ 'Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise' ]; var idbDomErrorNames = [ 'Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone' ]; var errorList = dexieErrorNames.concat(idbDomErrorNames); var defaultTexts = { VersionChanged: "Database version changed by other database connection", DatabaseClosed: "Database has been closed", Abort: "Transaction aborted", TransactionInactive: "Transaction has already completed or failed" }; // // DexieError - base class of all out exceptions. // function DexieError (name, msg) { // Reason we don't use ES6 classes is because: // 1. It bloats transpiled code and increases size of minified code. // 2. It doesn't give us much in this case. // 3. It would require sub classes to call super(), which // is not needed when deriving from Error. this._e = getErrorWithStack(); this.name = name; this.message = msg; } derive(DexieError).from(Error).extend({ stack: { get: function() { return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); } }, toString: function(){ return this.name + ": " + this.message; } }); function getMultiErrorMessage (msg, failures) { return msg + ". Errors: " + failures .map(f=>f.toString()) .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings .join('\n'); } // // ModifyError - thrown in WriteableCollection.modify() // Specific constructor because it contains members failures and failedKeys. // function ModifyError (msg, failures, successCount, failedKeys) { this._e = getErrorWithStack(); this.failures = failures; this.failedKeys = failedKeys; this.successCount = successCount; } derive(ModifyError).from(DexieError); function BulkError (msg, failures) { this._e = getErrorWithStack(); this.name = "BulkError"; this.failures = failures; this.message = getMultiErrorMessage(msg, failures); } derive(BulkError).from(DexieError); // // // Dynamically generate error names and exception classes based // on the names in errorList. // // // Map of {ErrorName -> ErrorName + "Error"} var errnames = errorList.reduce((obj,name)=>(obj[name]=name+"Error",obj),{}); // Need an alias for DexieError because we're gonna create subclasses with the same name. const BaseException = DexieError; // Map of {ErrorName -> exception constructor} var exceptions = errorList.reduce((obj,name)=>{ // Let the name be "DexieError" because this name may // be shown in call stack and when debugging. DexieError is // the most true name because it derives from DexieError, // and we cannot change Function.name programatically without // dynamically create a Function object, which would be considered // 'eval-evil'. var fullName = name + "Error"; function DexieError (msgOrInner, inner){ this._e = getErrorWithStack(); this.name = fullName; if (!msgOrInner) { this.message = defaultTexts[name] || fullName; this.inner = null; } else if (typeof msgOrInner === 'string') { this.message = msgOrInner; this.inner = inner || null; } else if (typeof msgOrInner === 'object') { this.message = `${msgOrInner.name} ${msgOrInner.message}`; this.inner = msgOrInner; } } derive(DexieError).from(BaseException); obj[name]=DexieError; return obj; },{}); // Use ECMASCRIPT standard exceptions where applicable: exceptions.Syntax = SyntaxError; exceptions.Type = TypeError; exceptions.Range = RangeError; var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{ obj[name + "Error"] = exceptions[name]; return obj; }, {}); function mapError (domError, message) { if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError; var rv = new exceptionMap[domError.name](message || domError.message, domError); if ("stack" in domError) { // Derive stack from inner exception if it has a stack setProp(rv, "stack", {get: function(){ return this.inner.stack; }}); } return rv; } var fullNameExceptions = errorList.reduce((obj, name)=>{ if (["Syntax","Type","Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name]; return obj; }, {}); fullNameExceptions.ModifyError = ModifyError; fullNameExceptions.DexieError = DexieError; fullNameExceptions.BulkError = BulkError; function Events(ctx) { var evs = {}; var rv = function (eventName, subscriber) { if (subscriber) { // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. var i = arguments.length, args = new Array(i - 1); while (--i) args[i - 1] = arguments[i]; evs[eventName].subscribe.apply(null, args); return ctx; } else if (typeof (eventName) === 'string') { // Return interface allowing to fire or unsubscribe from event return evs[eventName]; } }; rv.addEventType = add; for (var i = 1, l = arguments.length; i < l; ++i) { add(arguments[i]); } return rv; function add(eventName, chainFunction, defaultFunction) { if (typeof eventName === 'object') return addConfiguredEvents(eventName); if (!chainFunction) chainFunction = reverseStoppableEventChain; if (!defaultFunction) defaultFunction = nop; var context = { subscribers: [], fire: defaultFunction, subscribe: function (cb) { if (context.subscribers.indexOf(cb) === -1) { context.subscribers.push(cb); context.fire = chainFunction(context.fire, cb); } }, unsubscribe: function (cb) { context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); context.fire = context.subscribers.reduce(chainFunction, defaultFunction); } }; evs[eventName] = rv[eventName] = context; return context; } function addConfiguredEvents(cfg) { // events(this, {reading: [functionChain, nop]}); keys(cfg).forEach(function (eventName) { var args = cfg[eventName]; if (isArray(args)) { add(eventName, cfg[eventName][0], cfg[eventName][1]); } else if (args === 'asap') { // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. var context = add(eventName, mirror, function fire() { // Optimazation-safe cloning of arguments into args. var i = arguments.length, args = new Array(i); while (i--) args[i] = arguments[i]; // All each subscriber: context.subscribers.forEach(function (fn) { asap(function fireEvent() { fn.apply(null, args); }); }); }); } else throw new exceptions.InvalidArgument("Invalid event config"); }); } } // // Promise Class for Dexie library // // I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by // https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. // // Modifications needed to be done to support indexedDB because it wont accept setTimeout() // (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) . // This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 // // This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since // the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. // // In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another // tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use // another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick // engine that is used instead of setImmediate() or setTimeout(). // Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. // Also with inspiration from bluebird, asyncronic stacks in debug mode. // // Specific non-standard features of this Promise class: // * Async static context support (Promise.PSD) // * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame // and below + all promises that those promises creates or awaits. // * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). // // David Fahlander, https://github.com/dfahlander // // Just a pointer that only this module knows about. // Used in Promise constructor to emulate a private constructor. var INTERNAL = {}; // Async stacks (long stacks) must not grow infinitely. var LONG_STACKS_CLIP_LIMIT = 100; var MAX_LONG_STACKS = 20; var stack_being_generated = false; /* The default "nextTick" function used only for the very first promise in a promise chain. As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks emulated in this module. For indexedDB compatibility, this means that every method needs to execute at least one promise before doing an indexedDB operation. Dexie will always call db.ready().then() for every operation to make sure the indexedDB event is started in an emulated micro tick. */ var schedulePhysicalTick = (_global.setImmediate ? // setImmediate supported. Those modern platforms also supports Function.bind(). setImmediate.bind(null, physicalTick) : _global.MutationObserver ? // MutationObserver supported () => { var hiddenDiv = document.createElement("div"); (new MutationObserver(() => { physicalTick(); hiddenDiv = null; })).observe(hiddenDiv, { attributes: true }); hiddenDiv.setAttribute('i', '1'); } : // No support for setImmediate or MutationObserver. No worry, setTimeout is only called // once time. Every tick that follows will be our emulated micro tick. // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug ()=>{setTimeout(physicalTick,0);} ); // Confifurable through Promise.scheduler. // Don't export because it would be unsafe to let unknown // code call it unless they do try..catch within their callback. // This function can be retrieved through getter of Promise.scheduler though, // but users must not do Promise.scheduler (myFuncThatThrows exception)! var asap$1 = function (callback, args) { microtickQueue.push([callback, args]); if (needsNewPhysicalTick) { schedulePhysicalTick(); needsNewPhysicalTick = false; } }; var isOutsideMicroTick = true; var needsNewPhysicalTick = true; var unhandledErrors = []; var rejectingErrors = []; var currentFulfiller = null; var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions var globalPSD = { global: true, ref: 0, unhandleds: [], onunhandled: globalError, //env: null, // Will be set whenever leaving a scope using wrappers.snapshot() finalize: function () { this.unhandleds.forEach(uh => { try { globalError(uh[0], uh[1]); } catch (e) {} }); } }; var PSD = globalPSD; var microtickQueue = []; // Callbacks to call in this or next physical tick. var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. // Wrappers are not being used yet. Their framework is functioning and can be used // to replace environment during a PSD scope (a.k.a. 'zone'). /* **KEEP** export var wrappers = (() => { var wrappers = []; return { snapshot: () => { var i = wrappers.length, result = new Array(i); while (i--) result[i] = wrappers[i].snapshot(); return result; }, restore: values => { var i = wrappers.length; while (i--) wrappers[i].restore(values[i]); }, wrap: () => wrappers.map(w => w.wrap()), add: wrapper => { wrappers.push(wrapper); } }; })(); */ function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); this._listeners = []; this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() // execute the microtask engine implicitely within the call to resolve() or reject(). // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack // only contains library code when calling resolve() or reject(). // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from // global scope (event handler, timer etc)! this._lib = false; // Current async scope var psd = (this._PSD = PSD); if (debug) { this._stackHolder = getErrorWithStack(); this._prev = null; this._numPrev = 0; // Number of previous promises (for long stacks) linkToPreviousPromise(this, currentFulfiller); } if (typeof fn !== 'function') { if (fn !== INTERNAL) throw new TypeError('Not a function'); // Private constructor (INTERNAL, state, value). // Used internally by Promise.resolve() and Promise.reject(). this._state = arguments[1]; this._value = arguments[2]; if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). return; } this._state = null; // null (=pending), false (=rejected) or true (=resolved) this._value = null; // error or result ++psd.ref; // Refcounting current scope executePromiseTask(this, fn); } props(Promise.prototype, { then: function (onFulfilled, onRejected) { var rv = new Promise((resolve, reject) => { propagateToListener(this, new Listener(onFulfilled, onRejected, resolve, reject)); }); debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this); return rv; }, _then: function (onFulfilled, onRejected) { // A little tinier version of then() that don't have to create a resulting promise. propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); }, catch: function (onRejected) { if (arguments.length === 1) return this.then(null, onRejected); // First argument is the Error type to catch var type = arguments[0], handler = arguments[1]; return typeof type === 'function' ? this.then(null, err => // Catching errors by its constructor type (similar to java / c++ / c#) // Sample: promise.catch(TypeError, function (e) { ... }); err instanceof type ? handler(err) : PromiseReject(err)) : this.then(null, err => // Catching errors by the error.name property. Makes sense for indexedDB where error type // is always DOMError but where e.name tells the actual error type. // Sample: promise.catch('ConstraintError', function (e) { ... }); err && err.name === type ? handler(err) : PromiseReject(err)); }, finally: function (onFinally) { return this.then(value => { onFinally(); return value; }, err => { onFinally(); return PromiseReject(err); }); }, // Deprecate in next major. Needed only for db.on.error. uncaught: function (uncaughtHandler) { // Be backward compatible and use "onuncatched" as the event name on this. // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops. this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler); // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not // a previous promise. Reason: the prevous promise may lack onuncatched handler. if (this._state === false && unhandledErrors.indexOf(this) === -1) { // Replace unhandled error's destinaion promise with this one! unhandledErrors.some((p,i,l) => p._value === this._value && (l[i] = this)); // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could // take away this piece of code as well as the onuncatched and uncaught() method. } return this; }, stack: { get: function() { if (this._stack) return this._stack; try { stack_being_generated = true; var stacks = getStack (this, [], MAX_LONG_STACKS); var stack = stacks.join("\nFrom previous: "); if (this._state !== null) this._stack = stack; // Stack may be updated on reject. return stack; } finally { stack_being_generated = false; } } } }); function Listener(onFulfilled, onRejected, resolve, reject) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.resolve = resolve; this.reject = reject; this.psd = PSD; } // Promise Static Properties props (Promise, { all: function () { var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like. return new Promise(function (resolve, reject) { if (values.length === 0) resolve([]); var remaining = values.length; values.forEach((a,i) => Promise.resolve(a).then(x => { values[i] = x; if (!--remaining) resolve(values); }, reject)); }); }, resolve: value => { if (value instanceof Promise) return value; if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{ value.then(resolve, reject); }); return new Promise(INTERNAL, true, value); }, reject: PromiseReject, race: function () { var values = getArrayOf.apply(null, arguments); return new Promise((resolve, reject) => { values.map(value => Promise.resolve(value).then(resolve, reject)); }); }, PSD: { get: ()=>PSD, set: value => PSD = value }, newPSD: newScope, usePSD: usePSD, scheduler: { get: () => asap$1, set: value => {asap$1 = value;} }, rejectionMapper: { get: () => rejectionMapper, set: value => {rejectionMapper = value;} // Map reject failures }, follow: fn => { return new Promise((resolve, reject) => { return newScope((resolve, reject) => { var psd = PSD; psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. psd.finalize = callBoth(function () { // Unhandled standard or 3rd part promises are put in PSD.unhandleds and // examined upon scope completion while unhandled rejections in this Promise // will trigger directly through psd.onunhandled run_at_end_of_this_or_next_physical_tick(()=>{ this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]); }); }, psd.finalize); fn(); }, resolve, reject); }); }, on: Events(null, {"error": [ reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler }) }); var PromiseOnError = Promise.on.error; PromiseOnError.subscribe = deprecated ("Promise.on('error')", PromiseOnError.subscribe); PromiseOnError.unsubscribe = deprecated ("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe); /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function executePromiseTask (promise, fn) { // Promise Resolution Procedure: // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { fn(value => { if (promise._state !== null) return; if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); var shouldExecuteTick = promise._lib && beginMicroTickScope(); if (value && typeof value.then === 'function') { executePromiseTask(promise, (resolve, reject) => { value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject); }); } else { promise._state = true; promise._value = value; propagateAllListeners(promise); } if (shouldExecuteTick) endMicroTickScope(); }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below } catch (ex) { handleRejection(promise, ex); } } function handleRejection (promise, reason) { rejectingErrors.push(reason); if (promise._state !== null) return; var shouldExecuteTick = promise._lib && beginMicroTickScope(); reason = rejectionMapper(reason); promise._state = false; promise._value = reason; debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{ var origProp = getPropertyDescriptor(reason, "stack"); reason._promise = promise; setProp(reason, "stack", { get: () => stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack }); }); // Add the failure to a list of possibly uncaught errors addPossiblyUnhandledError(promise); propagateAllListeners(promise); if (shouldExecuteTick) endMicroTickScope(); } function propagateAllListeners (promise) { //debug && linkToPreviousPromise(promise); var listeners = promise._listeners; promise._listeners = []; for (var i = 0, len = listeners.length; i < len; ++i) { propagateToListener(promise, listeners[i]); } var psd = promise._PSD; --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); if (numScheduledCalls === 0) { // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, // and that no deferreds where listening to this rejection or success. // Since there is a risk that our stack can contain application code that may // do stuff after this code is finished that may generate new calls, we cannot // call finalizers here. ++numScheduledCalls; asap$1(()=>{ if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors }, []); } } function propagateToListener(promise, listener) { if (promise._state === null) { promise._listeners.push(listener); return; } var cb = promise._state ? listener.onFulfilled : listener.onRejected; if (cb === null) { // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() return (promise._state ? listener.resolve : listener.reject) (promise._value); } var psd = listener.psd; ++psd.ref; ++numScheduledCalls; asap$1 (callListener, [cb, promise, listener]); } function callListener (cb, promise, listener) { var outerScope = PSD; var psd = listener.psd; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } // Set static variable currentFulfiller to the promise that is being fullfilled, // so that we connect the chain of promises (for long stacks support) currentFulfiller = promise; // Call callback and resolve our listener with it's return value. var value = promise._value, ret; if (promise._state) { ret = cb (value); } else { if (rejectingErrors.length) rejectingErrors = []; ret = cb(value); if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. } listener.resolve(ret); } catch (e) { // Exception thrown in callback. Reject our listener. listener.reject(e); } finally { // Restore PSD, env and currentFulfiller. if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } currentFulfiller = null; if (--numScheduledCalls === 0) finalizePhysicalTick(); --psd.ref || psd.finalize(); } } function getStack (promise, stacks, limit) { if (stacks.length === limit) return stacks; var stack = ""; if (promise._state === false) { var failure = promise._value, errorName, message; if (failure != null) { errorName = failure.name || "Error"; message = failure.message || failure; stack = prettyStack(failure, 0); } else { errorName = failure; // If error is undefined or null, show that. message = ""; } stacks.push(errorName + (message ? ": " + message : "") + stack); } if (debug) { stack = prettyStack(promise._stackHolder, 2); if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); if (promise._prev) getStack(promise._prev, stacks, limit); } return stacks; } function linkToPreviousPromise(promise, prev) { // Support long stacks by linking to previous completed promise. var numPrev = prev ? prev._numPrev + 1 : 0; if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". promise._prev = prev; promise._numPrev = numPrev; } } /* The callback to schedule with setImmediate() or setTimeout(). It runs a virtual microtick and executes any callback registered in microtickQueue. */ function physicalTick() { beginMicroTickScope() && endMicroTickScope(); } function beginMicroTickScope() { var wasRootExec = isOutsideMicroTick; isOutsideMicroTick = false; needsNewPhysicalTick = false; return wasRootExec; } /* Executes micro-ticks without doing try..catch. This can be possible because we only use this internally and the registered functions are exception-safe (they do try..catch internally before calling any external method). If registering functions in the microtickQueue that are not exception-safe, this would destroy the framework and make it instable. So we don't export our asap method. */ function endMicroTickScope() { var callbacks, i, l; do { while (microtickQueue.length > 0) { callbacks = microtickQueue; microtickQueue = []; l = callbacks.length; for (i = 0; i < l; ++i) { var item = callbacks[i]; item[0].apply(null, item[1]); } } } while (microtickQueue.length > 0); isOutsideMicroTick = true; needsNewPhysicalTick = true; } function finalizePhysicalTick() { var unhandledErrs = unhandledErrors; unhandledErrors = []; unhandledErrs.forEach(p => { p._PSD.onunhandled.call(null, p._value, p); }); var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. var i = finalizers.length; while (i) finalizers[--i](); } function run_at_end_of_this_or_next_physical_tick (fn) { function finalizer() { fn(); tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); } tickFinalizers.push(finalizer); ++numScheduledCalls; asap$1(()=>{ if (--numScheduledCalls === 0) finalizePhysicalTick(); }, []); } function addPossiblyUnhandledError(promise) { // Only add to unhandledErrors if not already there. The first one to add to this list // will be upon the first rejection so that the root cause (first promise in the // rejection chain) is the one listed. if (!unhandledErrors.some(p => p._value === promise._value)) unhandledErrors.push(promise); } function markErrorAsHandled(promise) { // Called when a reject handled is actually being called. // Search in unhandledErrors for any promise whos _value is this promise_value (list // contains only rejected promises, and only one item per error) var i = unhandledErrors.length; while (i) if (unhandledErrors[--i]._value === promise._value) { // Found a promise that failed with this same error object pointer, // Remove that since there is a listener that actually takes care of it. unhandledErrors.splice(i, 1); return; } } // By default, log uncaught errors to the console function defaultErrorHandler(e) { console.warn(`Unhandled rejection: ${e.stack || e}`); } function PromiseReject (reason) { return new Promise(INTERNAL, false, reason); } function wrap (fn, errorCatcher) { var psd = PSD; return function() { var wasRootExec = beginMicroTickScope(), outerScope = PSD; try { if (outerScope !== psd) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn.apply(this, arguments); } catch (e) { errorCatcher && errorCatcher(e); } finally { if (outerScope !== psd) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } if (wasRootExec) endMicroTickScope(); } }; } function newScope (fn, a1, a2, a3) { var parent = PSD, psd = Object.create(parent); psd.parent = parent; psd.ref = 0; psd.global = false; // **KEEP** psd.env = wrappers.wrap(psd); // unhandleds and onunhandled should not be specifically set here. // Leave them on parent prototype. // unhandleds.push(err) will push to parent's prototype // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) ++parent.ref; psd.finalize = function () { --this.parent.ref || this.parent.finalize(); }; var rv = usePSD (psd, fn, a1, a2, a3); if (psd.ref === 0) psd.finalize(); return rv; } function usePSD (psd, fn, a1, a2, a3) { var outerScope = PSD; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn(a1, a2, a3); } finally { if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment. } } } const UNHANDLEDREJECTION = "unhandledrejection"; function globalError(err, promise) { var rv; try { rv = promise.onuncatched(err); } catch (e) {} if (rv !== false) try { var event, eventData = {promise: promise, reason: err}; if (_global.document && document.createEvent) { event = document.createEvent('Event'); event.initEvent(UNHANDLEDREJECTION, true, true); extend(event, eventData); } else if (_global.CustomEvent) { event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData}); extend(event, eventData); } if (event && _global.dispatchEvent) { dispatchEvent(event); if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. try {_global.onunhandledrejection(event);} catch (_) {} } if (!event.defaultPrevented) { // Backward compatibility: fire to events registered at Promise.on.error Promise.on.error.fire(err, promise); } } catch (e) {} } /* **KEEP** export function wrapPromise(PromiseClass) { var proto = PromiseClass.prototype; var origThen = proto.then; wrappers.add({ snapshot: () => proto.then, restore: value => {proto.then = value;}, wrap: () => patchedThen }); function patchedThen (onFulfilled, onRejected) { var promise = this; var onFulfilledProxy = wrap(function(value){ var rv = value; if (onFulfilled) { rv = onFulfilled(rv); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } --PSD.ref || PSD.finalize(); return rv; }); var onRejectedProxy = wrap(function(err){ promise._$err = err; var unhandleds = PSD.unhandleds; var idx = unhandleds.length, rv; while (idx--) if (unhandleds[idx]._$err === err) break; if (onRejected) { if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled. rv = onRejected(err); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } else { if (idx === -1) unhandleds.push(promise); rv = PromiseClass.reject(err); rv._$nointercept = true; // Prohibit eternal loop. } --PSD.ref || PSD.finalize(); return rv; }); if (this._$nointercept) return origThen.apply(this, arguments); ++PSD.ref; return origThen.call(this, onFulfilledProxy, onRejectedProxy); } } // Global Promise wrapper if (_global.Promise) wrapPromise(_global.Promise); */ doFakeAutoComplete(() => { // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. asap$1 = (fn, args) => { setTimeout(()=>{fn.apply(null, args);}, 0); }; }); function rejection (err, uncaughtHandler) { // Get the call stack and return a rejected promise. var rv = Promise.reject(err); return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv; } /* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.0-rc.3, Thu Oct 13 2016 * * http://dexie.org * * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var DEXIE_VERSION = '1.5.0-rc.3'; var maxString = String.fromCharCode(65535); var maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(); var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>."; var STRING_EXPECTED = "String expected."; var connections = []; var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); var hasIEDeleteObjectStoreBug = isIEOrEdge; var hangsOnDeleteLargeKeyRange = isIEOrEdge; var dexieStackFrameFilter = frame => !/(dexie\.js|dexie\.min\.js)/.test(frame); setDebug(debug, dexieStackFrameFilter); function Dexie(dbName, options) { /// <param name="options" type="Object" optional="true">Specify only if you wich to control which addons that should run on this instance</param> var deps = Dexie.dependencies; var opts = extend({ // Default Options addons: Dexie.addons, // Pick statically registered addons by default autoOpen: true, // Don't require db.open() explicitely. indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env. IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env. }, options); var addons = opts.addons, autoOpen = opts.autoOpen, indexedDB = opts.indexedDB, IDBKeyRange = opts.IDBKeyRange; var globalSchema = this._dbSchema = {}; var versions = []; var dbStoreNames = []; var allTables = {}; ///<var type="IDBDatabase" /> var idbdb = null; // Instance of IDBDatabase var dbOpenError = null; var isBeingOpened = false; var openComplete = false; var READONLY = "readonly", READWRITE = "readwrite"; var db = this; var dbReadyResolve, dbReadyPromise = new Promise(resolve => { dbReadyResolve = resolve; }), cancelOpen, openCanceller = new Promise((_, reject) => { cancelOpen = reject; }); var autoSchema = true; var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), hasGetAll; function init() { // Default subscribers to "versionchange" and "blocked". // Can be overridden by custom handlers. If custom handlers return false, these default // behaviours will be prevented. db.on("versionchange", function (ev) { // Default behavior for versionchange event is to close database connection. // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); // Let's not block the other window from making it's delete() or open() call. // NOTE! This event is never fired in IE,Edge or Safari. if (ev.newVersion > 0) console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`); else console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`); db.close(); // In many web applications, it would be recommended to force window.reload() // when this event occurs. To do that, subscribe to the versionchange event // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) // The reason for this is that your current web app obviously has old schema code that needs // to be updated. Another window got a newer version of the app and needs to upgrade DB but // your window is blocking it unless we close it here. }); db.on("blocked", ev => { if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn(`Dexie.delete('${db.name}') was blocked`); else console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`); }); } // // // // ------------------------- Versioning Framework--------------------------- // // // this.version = function (versionNumber) { /// <param name="versionNumber" type="Number"></param> /// <returns type="Version"></returns> if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); this.verno = Math.max(this.verno, versionNumber); var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; if (versionInstance) return versionInstance; versionInstance = new Version(versionNumber); versions.push(versionInstance); versions.sort(lowerVersionFirst); return versionInstance; }; function Version(versionNumber) { this._cfg = { version: versionNumber, storesSource: null, dbschema: {}, tables: {}, contentUpgrade: null }; this.stores({}); // Derive earlier schemas by default. } extend(Version.prototype, { stores: function (stores) { /// <summary> /// Defines the schema for a particular version /// </summary> /// <param name="stores" type="Object"> /// Example: <br/> /// {users: "id++,first,last,&amp;username,*email", <br/> /// passwords: "id++,&amp;username"}<br/> /// <br/> /// Syntax: {Table: "[primaryKey][++],[&amp;][*]index1,[&amp;][*]index2,..."}<br/><br/> /// Special characters:<br/> /// "&amp;" means unique key, <br/> /// "*" means value is multiEntry, <br/> /// "++" means auto-increment and only applicable for primary key <br/> /// </param> this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. var storesSpec = {}; versions.forEach(function (version) { // 'versions' is always sorted by lowest version first. extend(storesSpec, version._cfg.storesSource); }); var dbschema = (this._cfg.dbschema = {}); this._parseStoresSpec(storesSpec, dbschema); // Update the latest schema to this version // Update API globalSchema = db._dbSchema = dbschema; removeTablesApi([allTables, db, Transaction.prototype]); setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema); dbStoreNames = keys(dbschema); return this; }, upgrade: function (upgradeFunction) { /// <param name="upgradeFunction" optional="true">Function that performs upgrading actions.</param> var self = this; fakeAutoComplete(function () { upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema));// BUGBUG: No code completion for prev version's tables wont appear. }); this._cfg.contentUpgrade = upgradeFunction; return this; }, _parseStoresSpec: function (stores, outSchema) { keys(stores).forEach(function (tableName) { if (stores[tableName] !== null) { var instanceTemplate = {}; var indexes = parseIndexSyntax(stores[tableName]); var primKey = indexes.shift(); if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued"); if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); indexes.forEach(function (idx) { if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string"); setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); }); outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); } }); } }); function runUpgraders (oldVersion, idbtrans, reject) { var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); trans.create(idbtrans); trans._completion.catch(reject); var rejectTransaction = trans._reject.bind(trans); newScope(function () { PSD.trans = trans; if (oldVersion === 0) { // Create tables: keys(globalSchema).forEach(function (tableName) { createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); }); Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction); } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); }); } function updateTablesAndIndexes (oldVersion, trans, idbtrans) { // Upgrade version to version, step-by-step from oldest to newest version. // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) var queue = []; var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0]; if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; var anyContentUpgraderHasRun = false; var versToRun = versions.filter(v => v._cfg.version > oldVersion); versToRun.forEach(function (version) { /// <param name="version" type="Version"></param> queue.push(()=>{ var oldSchema = globalSchema; var newSchema = version._cfg.dbschema; adjustToExistingIndexNames(oldSchema, idbtrans); adjustToExistingIndexNames(newSchema, idbtrans); globalSchema = db._dbSchema = newSchema; var diff = getSchemaDiff(oldSchema, newSchema); // Add tables diff.add.forEach(function (tuple) { createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); }); // Change tables diff.change.forEach(function (change) { if (change.recreate) { throw new exceptions.Upgrade("Not yet support for changing primary key"); } else { var store = idbtrans.objectStore(change.name); // Add indexes change.add.forEach(function (idx) { addIndex(store, idx); }); // Update indexes change.change.forEach(function (idx) { store.deleteIndex(idx.name); addIndex(store, idx); }); // Delete indexes change.del.forEach(function (idxName) { store.deleteIndex(idxName); }); } }); if (version._cfg.contentUpgrade) { anyContentUpgraderHasRun = true; return Promise.follow(()=>{ version._cfg.contentUpgrade(trans); }); } }); queue.push(function (idbtrans) { if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of. var newSchema = version._cfg.dbschema; // Delete old tables deleteRemovedTables(newSchema, idbtrans); } }); }); // Now, create a queue execution engine function runQueue () { return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve(); } return runQueue().then(()=>{ createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) }); } function getSchemaDiff(oldSchema, newSchema) { var diff = { del: [], // Array of table names add: [], // Array of [tableName, newDefinition] change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} }; for (var table in oldSchema) { if (!newSchema[table]) diff.del.push(table); } for (table in newSchema) { var oldDef = oldSchema[table], newDef = newSchema[table]; if (!oldDef) { diff.add.push([table, newDef]); } else { var change = { name: table, def: newDef, recreate: false, del: [], add: [], change: [] }; if (oldDef.primKey.src !== newDef.primKey.src) { // Primary key has changed. Remove and re-add table. change.recreate = true; diff.change.push(change); } else { // Same primary key. Just find out what differs: var oldIndexes = oldDef.idxByName; var newIndexes = newDef.idxByName; for (var idxName in oldIndexes) { if (!newIndexes[idxName]) change.del.push(idxName); } for (idxName in newIndexes) { var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; if (!oldIdx) change.add.push(newIdx); else if (oldIdx.src !== newIdx.src) change.change.push(newIdx); } if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { diff.change.push(change); } } } } return diff; } function createTable(idbtrans, tableName, primKey, indexes) { /// <param name="idbtrans" type="IDBTransaction"></param> var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); indexes.forEach(function (idx) { addIndex(store, idx); }); return store; } function createMissingTables(newSchema, idbtrans) { keys(newSchema).forEach(function (tableName) { if (!idbtrans.db.objectStoreNames.contains(tableName)) { createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); } }); } function deleteRemovedTables(newSchema, idbtrans) { for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { var storeName = idbtrans.db.objectStoreNames[i]; if (newSchema[storeName] == null) { idbtrans.db.deleteObjectStore(storeName); } } } function addIndex(store, idx) { store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); } function dbUncaught(err) { return db.on.error.fire(err); } // // // Dexie Protected API // // this._allTables = allTables; this._tableFactory = function createTable(mode, tableSchema) { /// <param name="tableSchema" type="TableSchema"></param> if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection); else return new WriteableTable(tableSchema.name, tableSchema); }; this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new Transaction(mode, storeNames, dbschema, parentTransaction); }; /* Generate a temporary transaction when db operations are done outside a transactino scope. */ function tempTransaction(mode, storeNames, fn) { // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it. if (!openComplete && (!PSD.letThrough)) { if (!isBeingOpened) { if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught); db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn)); } else { var trans = db._createTransaction(mode, storeNames, globalSchema); return trans._promise(mode, function (resolve, reject) { newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise. PSD.trans = trans; fn(resolve, reject, trans); }); }).then(result => { // Instead of resolving value directly, wait with resolving it until transaction has completed. // Otherwise the data would not be in the DB if requesting it in the then() operation. // Specifically, to ensure that the following expression will work: // // db.friends.put({name: "Arne"}).then(function () { // db.friends.where("name").equals("Arne").count(function(count) { // assert (count === 1); // }); // }); // return trans._completion.then(()=>result); });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. trans._reject(err); return rejection(err); });*/ } } this._whenReady = function (fn) { return new Promise (fake || openComplete || PSD.letThrough ? fn : (resolve, reject) => { if (!isBeingOpened) { if (!autoOpen) { reject(new exceptions.DatabaseClosed()); return; } db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } dbReadyPromise.then(()=>{ fn(resolve, reject); }); }).uncaught(dbUncaught); }; // // // // // Dexie API // // // this.verno = 0; this.open = function () { if (isBeingOpened || idbdb) return dbReadyPromise.then(()=> dbOpenError ? rejection(dbOpenError, dbUncaught) : db); debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. isBeingOpened = true; dbOpenError = null; openComplete = false; // Function pointers to call when the core opening process completes. var resolveDbReady = dbReadyResolve, // upgradeTransaction to abort on failure. upgradeTransaction = null; return Promise.race([openCanceller, new Promise((resolve, reject) => { doFakeAutoComplete(()=>resolve()); // Make sure caller has specified at least one version if (versions.length > 0) autoSchema = false; // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: // IE fails when deleting objectStore after reading from it. // A future version of Dexie.js will stopover an intermediate version to workaround this. // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. // If no API, throw! if (!indexedDB) throw new exceptions.MissingAPI( "indexedDB API not found. If using IE10+, make sure to run your code on a server URL "+ "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = wrap(fireOnBlocked); req.onupgradeneeded = wrap (function (e) { upgradeTransaction = req.transaction; if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail. // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we // do not create a new database by accident here. req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) // Close database and delete it. req.result.close(); var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! delreq.onsuccess = delreq.onerror = wrap(function () { reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`)); }); } else { upgradeTransaction.onerror = wrap(eventRejectHandler(reject)); var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. runUpgraders(oldVer / 10, upgradeTransaction, reject, req); } }, reject); req.onsuccess = wrap (function () { // Core opening procedure complete. Now let's just record some stuff. upgradeTransaction = null; idbdb = req.result; connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. if (autoSchema) readGlobalSchema(); else if (idbdb.objectStoreNames.length > 0) { try { adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); } catch (e) { // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. } } idbdb.onversionchange = wrap(ev => { db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) db.on("versionchange").fire(ev); }); if (!hasNativeGetDatabaseNames) { // Update localStorage with list of database names globalDatabaseList(function (databaseNames) { if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName); }); } resolve(); }, reject); })]).then(()=>{ // Before finally resolving the dbReadyPromise and this promise, // call and await all on('ready') subscribers: // Dexie.vip() makes subscribers able to use the database while being opened. // This is a must since these subscribers take part of the opening procedure. return Dexie.vip(db.on.ready.fire); }).then(()=>{ // Resolve the db.open() with the db instance. isBeingOpened = false; return db; }).catch(err => { try { // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. upgradeTransaction && upgradeTransaction.abort(); } catch (e) { } isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught(). }).finally(()=>{ openComplete = true; resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. }); }; this.close = function () { var idx = connections.indexOf(db); if (idx >= 0) connections.splice(idx, 1); if (idbdb) { try {idbdb.close();} catch(e){} idbdb = null; } autoOpen = false; dbOpenError = new exceptions.DatabaseClosed(); if (isBeingOpened) cancelOpen(dbOpenError); // Reset dbReadyPromise promise: dbReadyPromise = new Promise(resolve => { dbReadyResolve = resolve; }); openCanceller = new Promise((_, reject) => { cancelOpen = reject; }); }; this.delete = function () { var hasArguments = arguments.length > 0; return new Promise(function (resolve, reject) { if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); if (isBeingOpened) { dbReadyPromise.then(doDelete); } else { doDelete(); } function doDelete() { db.close(); var req = indexedDB.deleteDatabase(dbName); req.onsuccess = wrap(function () { if (!hasNativeGetDatabaseNames) { globalDatabaseList(function(databaseNames) { var pos = databaseNames.indexOf(dbName); if (pos >= 0) return databaseNames.splice(pos, 1); }); } resolve(); }); req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = fireOnBlocked; } }).uncaught(dbUncaught); }; this.backendDB = function () { return idbdb; }; this.isOpen = function () { return idbdb !== null; }; this.hasFailed = function () { return dbOpenError !== null; }; this.dynamicallyOpened = function() { return autoSchema; }; // // Properties // this.name = dbName; // db.tables - an array of all Table instances. setProp(this, "tables", { get: function () { /// <returns type="Array" elementType="WriteableTable" /> return keys(allTables).map(function (name) { return allTables[name]; }); } }); // // Events // this.on = Events(this, "error", "populate", "blocked", "versionchange", {ready: [promisableChain, nop]}); this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe); this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe); this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) { return (subscriber, bSticky) => { Dexie.vip(()=>{ if (openComplete) { // Database already open. Call subscriber asap. if (!dbOpenError) Promise.resolve().then(subscriber); // bSticky: Also subscribe to future open sucesses (after close / reopen) if (bSticky) subscribe(subscriber); } else { // Database not yet open. Subscribe to it. subscribe(subscriber); // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. if (!bSticky) subscribe(function unsubscribe() { db.on.ready.unsubscribe(subscriber); db.on.ready.unsubscribe(unsubscribe); }); } }); } }); fakeAutoComplete(function () { db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); db.on("error").fire(new Error()); }); this.transaction = function (mode, tableInstances, scopeFunc) { /// <summary> /// /// </summary> /// <param name="mode" type="String">"r" for readonly, or "rw" for readwrite</param> /// <param name="tableInstances">Table instance, Array of Table instances, String or String Array of object stores to include in the transaction</param> /// <param name="scopeFunc" type="Function">Function to execute with transaction</param> // Let table arguments be all arguments between mode and last argument. var i = arguments.length; if (i < 2) throw new exceptions.InvalidArgument("Too few arguments"); // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) // and clone arguments except the first one into local var 'args'. var args = new Array(i - 1); while (--i) args[i-1] = arguments[i]; // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. scopeFunc = args.pop(); var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. var parentTransaction = PSD.trans; // Check if parent transactions is bound to this db instance, and if caller wants to reuse it if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null; var onlyIfCompatible = mode.indexOf('?') !== -1; mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. try { // // Get storeNames from arguments. Either through given table instances, or through given table names. // var storeNames = tables.map(table => { var storeName = table instanceof Table ? table.name : table; if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); return storeName; }); // // Resolve mode. Allow shortcuts "r" and "rw". // if (mode == "r" || mode == READONLY) mode = READONLY; else if (mode == "rw" || mode == READWRITE) mode = READWRITE; else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); if (parentTransaction) { // Basic checks if (parentTransaction.mode === READONLY && mode === READWRITE) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); } if (parentTransaction) { storeNames.forEach(function (storeName) { if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); } }); } } } catch (e) { return parentTransaction ? parentTransaction._promise(null, (_, reject) => {reject(e);}) : rejection (e, dbUncaught); } // If this is a sub-transaction, lock the parent and then launch the sub-transaction. return (parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady (enterTransactionScope)); function enterTransactionScope(resolve) { var parentPSD = PSD; resolve(Promise.resolve().then(()=>newScope(()=>{ // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). PSD.transless = PSD.transless || parentPSD; // Our transaction. //return new Promise((resolve, reject) => { var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); // Let the transaction instance be part of a Promise-specific data (PSD) value. PSD.trans = trans; if (parentTransaction) { // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) trans.idbtrans = parentTransaction.idbtrans; } else { trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. } // Provide arguments to the scope function (for backward compatibility) var tableArgs = storeNames.map(function (name) { return allTables[name]; }); tableArgs.push(trans); var returnValue; return Promise.follow(()=>{ // Finally, call the scope function with our table and transaction arguments. returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func. if (returnValue) { if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { // scopeFunc returned an iterator with throw-support. Handle yield as await. returnValue = awaitIterator(returnValue); } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) { throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString()); } } }).uncaught(dbUncaught).then(()=>{ if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion. return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well. }).then(()=>{ return returnValue; }).catch (e => { //reject(e); trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! return rejection(e); }); //}); }))); } }; this.table = function (tableName) { /// <returns type="WriteableTable"></returns> if (fake && autoSchema) return new WriteableTable(tableName); if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); } return allTables[tableName]; }; // // // // Table Class // // // function Table(name, tableSchema, collClass) { /// <param name="name" type="String"></param> this.name = name; this.schema = tableSchema; this.hook = allTables[name] ? allTables[name].hook : Events(null, { "creating": [hookCreatingChain, nop], "reading": [pureFunctionChain, mirror], "updating": [hookUpdatingChain, nop], "deleting": [hookDeletingChain, nop] }); this._collClass = collClass || Collection; } props(Table.prototype, { // // Table Protected Methods // _trans: function getTransaction(mode, fn, writeLocked) { var trans = PSD.trans; return trans && trans.db === db ? trans._promise (mode, fn, writeLocked) : tempTransaction (mode, [this.name], fn); }, _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion. var trans = PSD.trans, tableName = this.name; function supplyIdbStore (resolve, reject, trans) { fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); } return trans && trans.db === db ? trans._promise (mode, supplyIdbStore, writeLocked) : tempTransaction (mode, [this.name], supplyIdbStore); }, // // Table Public Methods // get: function (key, cb) { var self = this; return this._idbstore(READONLY, function (resolve, reject, idbstore) { fake && resolve(self.schema.instanceTemplate); var req = idbstore.get(key); req.onerror = eventRejectHandler(reject); req.onsuccess = wrap(function () { resolve(self.hook.reading.fire(req.result)); }, reject); }).then(cb); }, where: function (indexName) { return new WhereClause(this, indexName); }, count: function (cb) { return this.toCollection().count(cb); }, offset: function (offset) { return this.toCollection().offset(offset); }, limit: function (numRows) { return this.toCollection().limit(numRows); }, reverse: function () { return this.toCollection().reverse(); }, filter: function (filterFunction) { return this.toCollection().and(filterFunction); }, each: function (fn) { return this.toCollection().each(fn); }, toArray: function (cb) { return this.toCollection().toArray(cb); }, orderBy: function (index) { return new this._collClass(new WhereClause(this, index)); }, toCollection: function () { return new this._collClass(new WhereClause(this)); }, mapToClass: function (constructor, structure) { /// <summary> /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. /// </summary> /// <param name="constructor">Constructor function representing the class.</param> /// <param name="structure" optional="true">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], password}</param> this.schema.mappedClass = constructor; var instanceTemplate = Object.create(constructor.prototype); if (structure) { // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. applyStructure(instanceTemplate, structure); } this.schema.instanceTemplate = instanceTemplate; // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class // no matter which method to use for reading (Table.get() or Table.where(...)... ) var readHook = function (obj) { if (!obj) return obj; // No valid object. (Value is null). Return as is. // Create a new object that derives from constructor: var res = Object.create(constructor.prototype); // Clone members: for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){} return res; }; if (this.schema.readHook) { this.hook.reading.unsubscribe(this.schema.readHook); } this.schema.readHook = readHook; this.hook("reading", readHook); return constructor; }, defineClass: function (structure) { /// <summary> /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database /// as well as making it possible to extend the prototype of the returned constructor function. /// </summary> /// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param> return this.mapToClass(Dexie.defineClass(structure), structure); } }); // // // // WriteableTable Class (extends Table) // // // function WriteableTable(name, tableSchema, collClass) { Table.call(this, name, tableSchema, collClass || WriteableCollection); } function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => { errorList.push(e); done && done(); }); } function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], // else keysOrTuples must be just an array of keys: [key1, key2, ...]. return new Promise((resolve, reject)=>{ var len = keysOrTuples.length, lastItem = len - 1; if (len === 0) return resolve(); if (!hasDeleteHook) { for (var i=0; i < len; ++i) { var req = idbstore.delete(keysOrTuples[i]); req.onerror = wrap(eventRejectHandler(reject)); if (i === lastItem) req.onsuccess = wrap(()=>resolve()); } } else { var hookCtx, errorHandler = hookedEventRejectHandler(reject), successHandler = hookedEventSuccessHandler(null); tryCatch(()=> { for (var i = 0; i < len; ++i) { hookCtx = {onsuccess: null, onerror: null}; var tuple = keysOrTuples[i]; deletingHook.call(hookCtx, tuple[0], tuple[1], trans); var req = idbstore.delete(tuple[0]); req._hookCtx = hookCtx; req.onerror = errorHandler; if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve); else req.onsuccess = successHandler; } }, err=>{ hookCtx.onerror && hookCtx.onerror(err); throw err; }); } }).uncaught(dbUncaught); } derive(WriteableTable).from(Table).extend({ bulkDelete: function (keys$$1) { if (this.hook.deleting.fire === nop) { return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => { resolve (bulkDelete(idbstore, trans, keys$$1, false, nop)); }); } else { return this .where(':id') .anyOf(keys$$1) .delete() .then(()=>{}); // Resolve with undefined. } }, bulkPut: function(objects, keys$$1) { return this._idbstore(READWRITE, (resolve, reject, idbstore) => { if (!idbstore.keyPath && !this.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. const done = result => { if (errorList.length === 0) resolve(result); else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList)); }; var req, errorList = [], errorHandler, numObjs = objects.length, table = this; if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) { // // Standard Bulk (no 'creating' or 'updating' hooks to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } else { var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath)); // Generate map of {[key]: object} var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); var promise = !effectiveKeys ? // Auto-incremented key-less objects only without any keys argument. table.bulkAdd(objects) : // Keys provided. Either as inbound in provided objects, or as a keys argument. // Begin with updating those that exists in DB: table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () { this.value = objectLookup[this.primKey]; objectLookup[this.primKey] = null; // Mark as "don't add this" }).catch(ModifyError, e => { errorList = e.failures; // No need to concat here. These are the first errors added. }).then(()=> { // Now, let's examine which items didnt exist so we can add them: var objsToAdd = [], keysToAdd = keys$$1 && []; // Iterate backwards. Why? Because if same key was used twice, just add the last one. for (var i=effectiveKeys.length-1; i>=0; --i) { var key = effectiveKeys[i]; if (key == null || objectLookup[key]) { objsToAdd.push(objects[i]); keys$$1 && keysToAdd.push(key); if (key != null) objectLookup[key] = null; // Mark as "dont add again" } } // The items are in reverse order so reverse them before adding. // Could be important in order to get auto-incremented keys the way the caller // would expect. Could have used unshift instead of push()/reverse(), // but: http://jsperf.com/unshift-vs-reverse objsToAdd.reverse(); keys$$1 && keysToAdd.reverse(); return table.bulkAdd(objsToAdd, keysToAdd); }).then(lastAddedKey => { // Resolve with key of the last object in given arguments to bulkPut(): var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; }); promise.then(done).catch(BulkError, e => { // Concat failure from ModifyError and reject using our 'done' method. errorList = errorList.concat(e.failures); done(); }).catch(reject); } }, "locked"); // If called from transaction scope, lock transaction til all steps are done. }, bulkAdd: function(objects, keys$$1) { var self = this, creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. function done(result) { if (errorList.length === 0) resolve(result); else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList)); } var req, errorList = [], errorHandler, successHandler, numObjs = objects.length; if (creatingHook !== nop) { // // There are subscribers to hook('creating') // Must behave as documented. // var keyPath = idbstore.keyPath, hookCtx; errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); successHandler = hookedEventSuccessHandler(null); tryCatch(() => { for (var i=0, l = objects.length; i < l; ++i) { hookCtx = { onerror: null, onsuccess: null }; var key = keys$$1 && keys$$1[i]; var obj = objects[i], effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); if (effectiveKey == null && keyToUse != null) { if (keyPath) { obj = deepClone(obj); setByKeyPath(obj, keyPath, keyToUse); } else { key = keyToUse; } } req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; if (i < l - 1) { req.onerror = errorHandler; if (hookCtx.onsuccess) req.onsuccess = successHandler; } } }, err => { hookCtx.onerror && hookCtx.onerror(err); throw err; }); req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); req.onsuccess = hookedEventSuccessHandler(done); } else { // // Standard Bulk (no 'creating' hook to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } }); }, add: function (obj, key) { /// <summary> /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. /// </summary> /// <param name="obj" type="Object">A javascript object to insert</param> /// <param name="key" optional="true">Primary key</param> var creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { var hookCtx = {onsuccess: null, onerror: null}; if (creatingHook !== nop) { var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined); var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. if (effectiveKey == null && keyToUse != null) { // Using "==" and "!=" to check for either null or undefined! if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse); else key = keyToUse; } } try { var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; req.onerror = hookedEventRejectHandler(reject); req.onsuccess = hookedEventSuccessHandler(function (result) { // TODO: Remove these two lines in next major release (2.0?) // It's no good practice to have side effects on provided parameters var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, result); resolve(result); }); } catch (e) { if (hookCtx.onerror) hookCtx.onerror(e); throw e; } }); }, put: function (obj, key) { /// <summary> /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. /// </summary> /// <param name="obj" type="Object">A javascript object to insert or update</param> /// <param name="key" optional="true">Primary key</param> var self = this, creatingHook = this.hook.creating.fire, updatingHook = this.hook.updating.fire; if (creatingHook !== nop || updatingHook !== nop) { // // People listens to when("creating") or when("updating") events! // We must know whether the put operation results in an CREATE or UPDATE. // return this._trans(READWRITE, function (resolve, reject, trans) { // Since key is optional, make sure we get it from obj if not provided var effectiveKey = (key !== undefined) ? key : (self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath)); if (effectiveKey == null) { // "== null" means checking for either null or undefined. // No primary key. Must use add(). self.add(obj).then(resolve, reject); } else { // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). trans._lock(); // Needed because operation is splitted into modify() and add(). // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. obj = deepClone(obj); self.where(":id").equals(effectiveKey).modify(function () { // Replace extisting value with our object // CRUD event firing handled in WriteableCollection.modify() this.value = obj; }).then(function (count) { if (count === 0) { // Object's key was not found. Add the object instead. // CRUD event firing will be done in add() return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key. } else { return effectiveKey; // Resolve with the provided key. } }).finally(function () { trans._unlock(); }).then(resolve, reject); } }); } else { // Use the standard IDB put() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); req.onerror = eventRejectHandler(reject); req.onsuccess = function (ev) { var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, ev.target.result); resolve(req.result); }; }); } }, 'delete': function (key) { /// <param name="key">Primary key of the object to delete</param> if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted. return this.where(":id").equals(key).delete(); } else { // No one listens. Use standard IDB delete() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.delete(key); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, clear: function () { if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted. return this.toCollection().delete(); } else { return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.clear(); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, update: function (keyOrObject, modifications) { if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object."); if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { // object to modify. Also modify given object with the modifications: keys(modifications).forEach(function (keyPath) { setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); }); var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); if (key === undefined) return rejection(new exceptions.InvalidArgument( "Given object does not contain its primary key"), dbUncaught); return this.where(":id").equals(key).modify(modifications); } else { // key to modify return this.where(":id").equals(keyOrObject).modify(modifications); } } }); // // // // Transaction Class // // // function Transaction(mode, storeNames, dbschema, parent) { /// <summary> /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. /// </summary> /// <param name="mode" type="String">Any of "readwrite" or "readonly"</param> /// <param name="storeNames" type="Array">Array of table names to operate on</param> this.db = db; this.mode = mode; this.storeNames = storeNames; this.idbtrans = null; this.on = Events(this, "complete", "error", "abort"); this.parent = parent || null; this.active = true; this._tables = null; this._reculock = 0; this._blockedFuncs = []; this._psd = null; this._dbschema = dbschema; this._resolve = null; this._reject = null; this._completion = new Promise ((resolve, reject) => { this._resolve = resolve; this._reject = reject; }).uncaught(dbUncaught); this._completion.then( ()=> {this.on.complete.fire();}, e => { this.on.error.fire(e); this.parent ? this.parent._reject(e) : this.active && this.idbtrans && this.idbtrans.abort(); this.active = false; return rejection(e); // Indicate we actually DO NOT catch this error. }); } props(Transaction.prototype, { // // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) // _lock: function () { assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope. // Temporary set all requests into a pending queue if they are called before database is ready. ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this; return this; }, _unlock: function () { assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope. if (--this._reculock === 0) { if (!PSD.global) PSD.lockOwnerFor = null; while (this._blockedFuncs.length > 0 && !this._locked()) { var fn = this._blockedFuncs.shift(); try { fn(); } catch (e) { } } } return this; }, _locked: function () { // Checks if any write-lock is applied on this transaction. // To simplify the Dexie API for extension implementations, we support recursive locks. // This is accomplished by using "Promise Specific Data" (PSD). // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): // * callback given to the Promise() constructor (function (resolve, reject){...}) // * callbacks given to then()/catch()/finally() methods (function (value){...}) // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. // Derivation is done so that the inner PSD __proto__ points to the outer PSD. // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. return this._reculock && PSD.lockOwnerFor !== this; }, create: function (idbtrans) { assert(!this.idbtrans); if (!idbtrans && !idbdb) { switch (dbOpenError && dbOpenError.name) { case "DatabaseClosedError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.DatabaseClosed(dbOpenError); case "MissingAPIError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); default: // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! throw new exceptions.OpenFailed(dbOpenError); } } if (!this.active) throw new exceptions.TransactionInactive(); assert(this._completion._state === null); idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); idbtrans.onerror = wrap(ev => { preventDefault(ev);// Prohibit default bubbling to window.error this._reject(idbtrans.error); }); idbtrans.onabort = wrap(ev => { preventDefault(ev); this.active && this._reject(new exceptions.Abort()); this.active = false; this.on("abort").fire(ev); }); idbtrans.oncomplete = wrap(() => { this.active = false; this._resolve(); }); return this; }, _promise: function (mode, fn, bWriteLock) { var self = this; return newScope(function() { var p; // Read lock always if (!self._locked()) { p = self.active ? new Promise(function (resolve, reject) { if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly"); if (!self.idbtrans && mode) self.create(); if (bWriteLock) self._lock(); // Write lock if write operation is requested fn(resolve, reject, self); }) : rejection(new exceptions.TransactionInactive()); if (self.active && bWriteLock) p.finally(function () { self._unlock(); }); } else { // Transaction is write-locked. Wait for mutex. p = new Promise(function (resolve, reject) { self._blockedFuncs.push(function () { self._promise(mode, fn, bWriteLock).then(resolve, reject); }); }); } p._lib = true; return p.uncaught(dbUncaught); }); }, // // Transaction Public Properties and Methods // abort: function () { this.active && this._reject(new exceptions.Abort()); this.active = false; }, tables: { get: deprecated ("Transaction.tables", function () { return arrayToObject(this.storeNames, name => [name, allTables[name]]); }, "Use db.tables()") }, complete: deprecated ("Transaction.complete()", function (cb) { return this.on("complete", cb); }), error: deprecated ("Transaction.error()", function (cb) { return this.on("error", cb); }), table: deprecated ("Transaction.table()", function (name) { if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction"); return allTables[name]; }) }); // // // // WhereClause // // // function WhereClause(table, index, orCollection) { /// <param name="table" type="Table"></param> /// <param name="index" type="String" optional="true"></param> /// <param name="orCollection" type="Collection" optional="true"></param> this._ctx = { table: table, index: index === ":id" ? null : index, collClass: table._collClass, or: orCollection }; } props(WhereClause.prototype, function () { // WhereClause private methods function fail(collectionOrWhereClause, err, T) { var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause; collection._ctx.error = T ? new T(err) : new TypeError(err); return collection; } function emptyCollection(whereClause) { return new whereClause._ctx.collClass(whereClause, function() { return IDBKeyRange.only(""); }).limit(0); } function upperFactory(dir) { return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; } function lowerFactory(dir) { return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; } function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { var length = Math.min(key.length, lowerNeedle.length); var llp = -1; for (var i = 0; i < length; ++i) { var lwrKeyChar = lowerKey[i]; if (lwrKeyChar !== lowerNeedle[i]) { if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); return null; } if (cmp(key[i], lwrKeyChar) < 0) llp = i; } if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length); if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length); return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); } function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { /// <param name="needles" type="Array" elementType="String"></param> var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; if (!needles.every(s => typeof s === 'string')) { return fail(whereClause, STRING_EXPECTED); } function initDirection(dir) { upper = upperFactory(dir); lower = lowerFactory(dir); compare = (dir === "next" ? simpleCompare : simpleCompareReverse); var needleBounds = needles.map(function (needle){ return {lower: lower(needle), upper: upper(needle)}; }).sort(function(a,b) { return compare(a.lower, b.lower); }); upperNeedles = needleBounds.map(function (nb){ return nb.upper; }); lowerNeedles = needleBounds.map(function (nb){ return nb.lower; }); direction = dir; nextKeySuffix = (dir === "next" ? "" : suffix); } initDirection("next"); var c = new whereClause._ctx.collClass(whereClause, function() { return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix); }); c._ondirectionchange = function (direction) { // This event onlys occur before filter is called the first time. initDirection(direction); }; var firstPossibleNeedle = 0; c._addAlgorithm(function (cursor, advance, resolve) { /// <param name="cursor" type="IDBCursor"></param> /// <param name="advance" type="Function"></param> /// <param name="resolve" type="Function"></param> var key = cursor.key; if (typeof key !== 'string') return false; var lowerKey = lower(key); if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { return true; } else { var lowestPossibleCasing = null; for (var i=firstPossibleNeedle; i<needlesLen; ++i) { var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1; else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { lowestPossibleCasing = casing; } } if (lowestPossibleCasing !== null) { advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); } else { advance(resolve); } return false; } }); return c; } // // WhereClause public methods // return { between: function (lower, upper, includeLower, includeUpper) { /// <summary> /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. /// </summary> /// <param name="lower"></param> /// <param name="upper"></param> /// <param name="includeLower" optional="true">Whether items that equals lower should be included. Default true.</param> /// <param name="includeUpper" optional="true">Whether items that equals upper should be included. Default false.</param> /// <returns type="Collection"></returns> includeLower = includeLower !== false; // Default to true includeUpper = includeUpper === true; // Default to false try { if ((cmp(lower, upper) > 0) || (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. return new this._ctx.collClass(this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } }, equals: function (value) { return new this._ctx.collClass(this, function() { return IDBKeyRange.only(value); }); }, above: function (value) { return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value, true); }); }, aboveOrEqual: function (value) { return new this._ctx.collClass(this, function() { return IDBKeyRange.lowerBound(value); }); }, below: function (value) { return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value, true); }); }, belowOrEqual: function (value) { return new this._ctx.collClass(this, function() { return IDBKeyRange.upperBound(value); }); }, startsWith: function (str) { /// <param name="str" type="String"></param> if (typeof str !== 'string') return fail(this, STRING_EXPECTED); return this.between(str, str + maxString, true, true); }, startsWithIgnoreCase: function (str) { /// <param name="str" type="String"></param> if (str === "") return this.startsWith(str); return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); }, equalsIgnoreCase: function (str) { /// <param name="str" type="String"></param> return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); }, anyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); }, startsWithAnyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function(n){ return x.indexOf(n) === 0; });}, set, maxString); }, anyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); var compare = ascending; try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); } if (set.length === 0) return emptyCollection(this); var c = new this._ctx.collClass(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); c._ondirectionchange = function (direction) { compare = (direction === "next" ? ascending : descending); set.sort(compare); }; var i = 0; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (compare(key, set[i]) > 0) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (compare(key, set[i]) === 0) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function () { cursor.continue(set[i]); }); return false; } }); return c; }, notEqual: function(value) { return this.inAnyRange([[-Infinity, value],[value, maxKey]], {includeLowers: false, includeUppers: false}); }, noneOf: function() { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection. try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);} // Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]] var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; }, null); ranges.push([set[set.length - 1], maxKey]); return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false}); }, /** Filter out values withing given set of ranges. * Example, give children and elders a rebate of 50%: * * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); * * @param {(string|number|Date|Array)[][]} ranges * @param {{includeLowers: boolean, includeUppers: boolean}} options */ inAnyRange: function (ranges, options) { var ctx = this._ctx; if (ranges.length === 0) return emptyCollection(this); if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) { return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); } var includeLowers = !options || options.includeLowers !== false; // Default to true var includeUppers = options && options.includeUppers === true; // Default to false function addRange (ranges, newRange) { for (var i=0,l=ranges.length;i<l;++i) { var range = ranges[i]; if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { range[0] = min(range[0], newRange[0]); range[1] = max(range[1], newRange[1]); break; } } if (i === l) ranges.push(newRange); return ranges; } var sortDirection = ascending; function rangeSorter(a,b) { return sortDirection(a[0], b[0]);} // Join overlapping ranges var set; try { set = ranges.reduce(addRange, []); set.sort(rangeSorter); } catch(ex) { return fail(this, INVALID_KEY_ARGUMENT); } var i = 0; var keyIsBeyondCurrentEntry = includeUppers ? function(key) { return ascending(key, set[i][1]) > 0; } : function(key) { return ascending(key, set[i][1]) >= 0; }; var keyIsBeforeCurrentEntry = includeLowers ? function(key) { return descending(key, set[i][0]) > 0; } : function(key) { return descending(key, set[i][0]) >= 0; }; function keyWithinCurrentRange (key) { return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); } var checkKey = keyIsBeyondCurrentEntry; var c = new ctx.collClass(this, function () { return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); }); c._ondirectionchange = function (direction) { if (direction === "next") { checkKey = keyIsBeyondCurrentEntry; sortDirection = ascending; } else { checkKey = keyIsBeforeCurrentEntry; sortDirection = descending; } set.sort(rangeSorter); }; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (checkKey(key)) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (keyWithinCurrentRange(key)) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) { // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. // Continue to next key but don't include this one. return false; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function() { if (sortDirection === ascending) cursor.continue(set[i][0]); else cursor.continue(set[i][1]); }); return false; } }); return c; }, startsWithAnyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (!set.every(function (s) { return typeof s === 'string'; })) { return fail(this, "startsWithAnyOf() only works with strings"); } if (set.length === 0) return emptyCollection(this); return this.inAnyRange(set.map(function(str) { return [str, str + maxString]; })); } }; }); // // // // Collection Class // // // function Collection(whereClause, keyRangeGenerator) { /// <summary> /// /// </summary> /// <param name="whereClause" type="WhereClause">Where clause instance</param> /// <param name="keyRangeGenerator" value="function(){ return IDBKeyRange.bound(0,1);}" optional="true"></param> var keyRange = null, error = null; if (keyRangeGenerator) try { keyRange = keyRangeGenerator(); } catch (ex) { error = ex; } var whereCtx = whereClause._ctx, table = whereCtx.table; this._ctx = { table: table, index: whereCtx.index, isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), range: keyRange, keysOnly: false, dir: "next", unique: "", algorithm: null, filter: null, replayFilter: null, justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all) isMatch: null, offset: 0, limit: Infinity, error: error, // If set, any promise must be rejected with this error or: whereCtx.or, valueMapper: table.hook.reading.fire }; } function isPlainKeyRange (ctx, ignoreLimitFilter) { return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); } props(Collection.prototype, function () { // // Collection Private Functions // function addFilter(ctx, fn) { ctx.filter = combine(ctx.filter, fn); } function addReplayFilter (ctx, factory, isLimitFilter) { var curr = ctx.replayFilter; ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory; ctx.justLimit = isLimitFilter && !curr; } function addMatchFilter(ctx, fn) { ctx.isMatch = combine(ctx.isMatch, fn); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string * } * @param store IDBObjectStore **/ function getIndexOrStore(ctx, store) { if (ctx.isPrimKey) return store; var indexSpec = ctx.table.schema.idxByName[ctx.index]; if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); return store.index(indexSpec.name); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string, * keysOnly: boolean, * range?: IDBKeyRange, * dir: "next" | "prev" * } */ function openCursor(ctx, store) { var idxOrStore = getIndexOrStore(ctx, store); return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); } function iter(ctx, fn, resolve, reject, idbstore) { var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; if (!ctx.or) { iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); } else (()=>{ var set = {}; var resolved = 0; function resolveboth() { if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. } function union(item, cursor, advance) { if (!filter || filter(cursor, advance, resolveboth, reject)) { var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string if (!hasOwn(set, key)) { set[key] = true; fn(item, cursor, advance); } } } ctx.or._iterate(union, resolveboth, reject, idbstore); iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); })(); } function getInstanceTemplate(ctx) { return ctx.table.schema.instanceTemplate; } return { // // Collection Protected Functions // _read: function (fn, cb) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); }); else return ctx.table._idbstore(READONLY, fn).then(cb); }, _write: function (fn) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); }); else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. }, _addAlgorithm: function (fn) { var ctx = this._ctx; ctx.algorithm = combine(ctx.algorithm, fn); }, _iterate: function (fn, resolve, reject, idbstore) { return iter(this._ctx, fn, resolve, reject, idbstore); }, clone: function (props$$1) { var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); if (props$$1) extend(ctx, props$$1); rv._ctx = ctx; return rv; }, raw: function () { this._ctx.valueMapper = null; return this; }, // // Collection Public methods // each: function (fn) { var ctx = this._ctx; if (fake) { var item = getInstanceTemplate(ctx), primKeyPath = ctx.table.schema.primKey.keyPath, key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), primaryKey = getByKeyPath(item, primKeyPath); fn(item, {key: key, primaryKey: primaryKey}); } return this._read(function (resolve, reject, idbstore) { iter(ctx, fn, resolve, reject, idbstore); }); }, count: function (cb) { if (fake) return Promise.resolve(0).then(cb); var ctx = this._ctx; if (isPlainKeyRange(ctx, true)) { // This is a plain key range. We can use the count() method if the index. return this._read(function (resolve, reject, idbstore) { var idx = getIndexOrStore(ctx, idbstore); var req = (ctx.range ? idx.count(ctx.range) : idx.count()); req.onerror = eventRejectHandler(reject); req.onsuccess = function (e) { resolve(Math.min(e.target.result, ctx.limit)); }; }, cb); } else { // Algorithms, filters or expressions are applied. Need to count manually. var count = 0; return this._read(function (resolve, reject, idbstore) { iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore); }, cb); } }, sortBy: function (keyPath, cb) { /// <param name="keyPath" type="String"></param> var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; function getval(obj, i) { if (i) return getval(obj[parts[i]], i - 1); return obj[lastPart]; } var order = this._ctx.dir === "next" ? 1 : -1; function sorter(a, b) { var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); return aVal < bVal ? -order : aVal > bVal ? order : 0; } return this.toArray(function (a) { return a.sort(sorter); }).then(cb); }, toArray: function (cb) { var ctx = this._ctx; return this._read(function (resolve, reject, idbstore) { fake && resolve([getInstanceTemplate(ctx)]); if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAll() or // IDBKeyRange.getAll(): var readingHook = ctx.table.hook.reading.fire; var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(res => { try {resolve (res.map(readingHook));} catch(e) {reject(e);} })); } else { // Getting array through a cursor. var a = []; iter(ctx, function (item) { a.push(item); }, function arrayComplete() { resolve(a); }, reject, idbstore); } }, cb); }, offset: function (offset) { var ctx = this._ctx; if (offset <= 0) return this; ctx.offset += offset; // For count() if (isPlainKeyRange(ctx)) { addReplayFilter(ctx, ()=> { var offsetLeft = offset; return (cursor, advance) => { if (offsetLeft === 0) return true; if (offsetLeft === 1) { --offsetLeft; return false; } advance(()=> { cursor.advance(offsetLeft); offsetLeft = 0; }); return false; }; }); } else { addReplayFilter(ctx, ()=> { var offsetLeft = offset; return () => (--offsetLeft < 0); }); } return this; }, limit: function (numRows) { this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() addReplayFilter(this._ctx, ()=> { var rowsLeft = numRows; return function (cursor, advance, resolve) { if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. }; }, true); return this; }, until: function (filterFunction, bIncludeStopEntry) { var ctx = this._ctx; fake && filterFunction(getInstanceTemplate(ctx)); addFilter(this._ctx, function (cursor, advance, resolve) { if (filterFunction(cursor.value)) { advance(resolve); return bIncludeStopEntry; } else { return true; } }); return this; }, first: function (cb) { return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); }, last: function (cb) { return this.reverse().first(cb); }, filter: function (filterFunction) { /// <param name="jsFunctionFilter" type="Function">function(val){return true/false}</param> fake && filterFunction(getInstanceTemplate(this._ctx)); addFilter(this._ctx, function (cursor) { return filterFunction(cursor.value); }); // match filters not used in Dexie.js but can be used by 3rd part libraries to test a // collection for a match without querying DB. Used by Dexie.Observable. addMatchFilter(this._ctx, filterFunction); return this; }, and: function (filterFunction) { return this.filter(filterFunction); }, or: function (indexName) { return new WhereClause(this._ctx.table, indexName, this); }, reverse: function () { this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir); return this; }, desc: function () { return this.reverse(); }, eachKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.key, cursor); }); }, eachUniqueKey: function (cb) { this._ctx.unique = "unique"; return this.eachKey(cb); }, eachPrimaryKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); }, keys: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.key); }).then(function () { return a; }).then(cb); }, primaryKeys: function (cb) { var ctx = this._ctx; if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAllKeys() or // IDBKeyRange.getAllKeys(): return this._read((resolve, reject, idbstore) =>{ var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = eventSuccessHandler(resolve); }).then(cb); } ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.primaryKey); }).then(function () { return a; }).then(cb); }, uniqueKeys: function (cb) { this._ctx.unique = "unique"; return this.keys(cb); }, firstKey: function (cb) { return this.limit(1).keys(function (a) { return a[0]; }).then(cb); }, lastKey: function (cb) { return this.reverse().firstKey(cb); }, distinct: function () { var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes. var set = {}; addFilter(this._ctx, function (cursor) { var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string var found = hasOwn(set, strKey); set[strKey] = true; return !found; }); return this; } }; }); // // // WriteableCollection Class // // function WriteableCollection() { Collection.apply(this, arguments); } derive(WriteableCollection).from(Collection).extend({ // // WriteableCollection Public Methods // modify: function (changes) { var self = this, ctx = this._ctx, hook = ctx.table.hook, updatingHook = hook.updating.fire, deletingHook = hook.deleting.fire; fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); return this._write(function (resolve, reject, idbstore, trans) { var modifyer; if (typeof changes === 'function') { // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) if (updatingHook === nop && deletingHook === nop) { // Noone cares about what is being changed. Just let the modifier function be the given argument as is. modifyer = changes; } else { // People want to know exactly what is being modified or deleted. // Let modifyer be a proxy function that finds out what changes the caller is actually doing // and call the hooks accordingly! modifyer = function (item) { var origItem = deepClone(item); // Clone the item first so we can compare laters. if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) if (!hasOwn(this, "value")) { // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. deletingHook.call(this, this.primKey, item, trans); } else { // No deletion. Check what was changed var objectDiff = getObjectDiff(origItem, this.value); var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); if (additionalChanges) { // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. item = this.value; keys(additionalChanges).forEach(function (keyPath) { setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath }); } } }; } } else if (updatingHook === nop) { // changes is a set of {keyPath: value} and no one is listening to the updating hook. var keyPaths = keys(changes); var numKeys = keyPaths.length; modifyer = function (item) { var anythingModified = false; for (var i = 0; i < numKeys; ++i) { var keyPath = keyPaths[i], val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath anythingModified = true; } } return anythingModified; }; } else { // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and // allow it to add additional modifications to make. var origChanges = changes; changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. modifyer = function (item) { var anythingModified = false; var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); if (additionalChanges) extend(changes, additionalChanges); keys(changes).forEach(function (keyPath) { var val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); anythingModified = true; } }); if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration return anythingModified; }; } var count = 0; var successCount = 0; var iterationComplete = false; var failures = []; var failKeys = []; var currentKey = null; function modifyItem(item, cursor) { currentKey = cursor.primaryKey; var thisContext = { primKey: cursor.primaryKey, value: item, onsuccess: null, onerror: null }; function onerror(e) { failures.push(e); failKeys.push(thisContext.primKey); checkFinished(); return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction } if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update! var bDelete = !hasOwn(thisContext, "value"); ++count; tryCatch(function () { var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value)); req._hookCtx = thisContext; req.onerror = hookedEventRejectHandler(onerror); req.onsuccess = hookedEventSuccessHandler(function () { ++successCount; checkFinished(); }); }, onerror); } else if (thisContext.onsuccess) { // Hook will expect either onerror or onsuccess to always be called! thisContext.onsuccess(thisContext.value); } } function doReject(e) { if (e) { failures.push(e); failKeys.push(currentKey); } return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); } function checkFinished() { if (iterationComplete && successCount + failures.length === count) { if (failures.length > 0) doReject(); else resolve(successCount); } } self.clone().raw()._iterate(modifyItem, function () { iterationComplete = true; checkFinished(); }, doReject, idbstore); }); }, 'delete': function () { var ctx = this._ctx, range = ctx.range, deletingHook = ctx.table.hook.deleting.fire, hasDeleteHook = deletingHook !== nop; if (!hasDeleteHook && isPlainKeyRange(ctx) && ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear(). { // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) // For chromium, this is the way most optimized version. // For IE/Edge, this could hang the indexedDB engine and make operating system instable // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) return this._write((resolve, reject, idbstore) => { // Our API contract is to return a count of deleted items, so we have to count() before delete(). var onerror = eventRejectHandler(reject), countReq = (range ? idbstore.count(range) : idbstore.count()); countReq.onerror = onerror; countReq.onsuccess = () => { var count = countReq.result; tryCatch(()=> { var delReq = (range ? idbstore.delete(range) : idbstore.clear()); delReq.onerror = onerror; delReq.onsuccess = () => resolve(count); }, err => reject(err)); }; }); } // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. // Divide into chunks to not starve RAM. // If has delete hook, we will have to collect not just keys but also objects, so it will use // more memory and need lower chunk size. const CHUNKSIZE = hasDeleteHook ? 2000 : 10000; return this._write((resolve, reject, idbstore, trans) => { var totalCount = 0; // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. var collection = this .clone({ keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers) .distinct() // In case multiEntry is used, never delete same key twice because resulting count // would become larger than actual delete count. .limit(CHUNKSIZE) .raw(); // Don't filter through reading-hooks (like mapped classes etc) var keysOrTuples = []; // We're gonna do things on as many chunks that are needed. // Use recursion of nextChunk function: const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => { // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, // so that the hook can be called with its values in bulkDelete(). keysOrTuples.push([cursor.primaryKey, cursor.value]); } : (val, cursor) => { // No one subscribes to hook('deleting'). Collect only primary keys: keysOrTuples.push(cursor.primaryKey); }).then(() => { // Chromium deletes faster when doing it in sort order. hasDeleteHook ? keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) : keysOrTuples.sort(ascending); return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); }).then(()=> { var count = keysOrTuples.length; totalCount += count; keysOrTuples = []; return count < CHUNKSIZE ? totalCount : nextChunk(); }); resolve (nextChunk()); }); } }); // // // // ------------------------- Help functions --------------------------- // // // function lowerVersionFirst(a, b) { return a._cfg.version - b._cfg.version; } function setApiOnPlace(objs, tableNames, mode, dbschema) { tableNames.forEach(function (tableName) { var tableInstance = db._tableFactory(mode, dbschema[tableName]); objs.forEach(function (obj) { tableName in obj || (obj[tableName] = tableInstance); }); }); } function removeTablesApi(objs) { objs.forEach(function (obj) { for (var key in obj) { if (obj[key] instanceof Table) delete obj[key]; } }); } function iterate(req, filter, fn, resolve, reject, valueMapper) { // Apply valueMapper (hook('reading') or mappped class) var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn; // Wrap fn with PSD and microtick stuff from Promise. var wrappedFn = wrap(mappedFn, reject); if (!req.onerror) req.onerror = eventRejectHandler(reject); if (filter) { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } else { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } } function parseIndexSyntax(indexes) { /// <param name="indexes" type="String"></param> /// <returns type="Array" elementType="IndexSpec"></returns> var rv = []; indexes.split(',').forEach(function (index) { index = index.trim(); var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" // Let keyPath of "[a+b]" be ["a","b"]: var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; rv.push(new IndexSpec( name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index) )); }); return rv; } function cmp(key1, key2) { return indexedDB.cmp(key1, key2); } function min(a, b) { return cmp(a, b) < 0 ? a : b; } function max(a, b) { return cmp(a, b) > 0 ? a : b; } function ascending(a,b) { return indexedDB.cmp(a,b); } function descending(a, b) { return indexedDB.cmp(b,a); } function simpleCompare(a, b) { return a < b ? -1 : a === b ? 0 : 1; } function simpleCompareReverse(a, b) { return a > b ? -1 : a === b ? 0 : 1; } function combine(filter1, filter2) { return filter1 ? filter2 ? function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : filter1 : filter2; } function readGlobalSchema() { db.verno = idbdb.version / 10; db._dbSchema = globalSchema = {}; dbStoreNames = slice(idbdb.objectStoreNames, 0); if (dbStoreNames.length === 0) return; // Database contains no stores. var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); dbStoreNames.forEach(function (storeName) { var store = trans.objectStore(storeName), keyPath = store.keyPath, dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); var indexes = []; for (var j = 0; j < store.indexNames.length; ++j) { var idbindex = store.index(store.indexNames[j]); keyPath = idbindex.keyPath; dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); indexes.push(index); } globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); }); setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema); } function adjustToExistingIndexNames(schema, idbtrans) { /// <summary> /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db /// </summary> /// <param name="schema" type="Object">Map between name and TableSchema</param> /// <param name="idbtrans" type="IDBTransaction"></param> var storeNames = idbtrans.db.objectStoreNames; for (var i = 0; i < storeNames.length; ++i) { var storeName = storeNames[i]; var store = idbtrans.objectStore(storeName); hasGetAll = 'getAll' in store; for (var j = 0; j < store.indexNames.length; ++j) { var indexName = store.indexNames[j]; var keyPath = store.index(indexName).keyPath; var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; if (schema[storeName]) { var indexSpec = schema[storeName].idxByName[dexieName]; if (indexSpec) indexSpec.name = indexName; } } } } function fireOnBlocked(ev) { db.on("blocked").fire(ev); // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: connections .filter(c=>c.name === db.name && c !== db && !c._vcFired) .map(c => c.on("versionchange").fire(ev)); } extend(this, { Collection: Collection, Table: Table, Transaction: Transaction, Version: Version, WhereClause: WhereClause, WriteableCollection: WriteableCollection, WriteableTable: WriteableTable }); init(); addons.forEach(function (fn) { fn(db); }); } var fakeAutoComplete = function () { };// Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) function parseType(type) { if (typeof type === 'function') { return new type(); } else if (isArray(type)) { return [parseType(type[0])]; } else if (type && typeof type === 'object') { var rv = {}; applyStructure(rv, type); return rv; } else { return type; } } function applyStructure(obj, structure) { keys(structure).forEach(function (member) { var value = parseType(structure[member]); obj[member] = value; }); return obj; } function eventSuccessHandler(done) { return function (ev) { done(ev.target.result); } } function hookedEventSuccessHandler(resolve) { // wrap() is needed when calling hooks because the rare scenario of: // * hook does a db operation that fails immediately (IDB throws exception) // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. // wrap() will also execute in a virtual tick. // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. // * If this was the last event in the bulk, the promise will resolve after a physical tick // and the transaction will have committed already. // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, // because it is always marked with _lib = true when created using Transaction._promise(). return wrap(function(event) { var req = event.target, result = req.result, ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance. hookSuccessHandler = ctx && ctx.onsuccess; hookSuccessHandler && hookSuccessHandler(result); resolve && resolve(result); }, resolve); } function eventRejectHandler(reject) { return function (event) { preventDefault(event); reject (event.target.error); return false; }; } function hookedEventRejectHandler (reject) { return wrap(function (event) { // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. var req = event.target, err = req.error, ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance. hookErrorHandler = ctx && ctx.onerror; hookErrorHandler && hookErrorHandler(err); preventDefault(event); reject (err); return false; }); } function preventDefault(event) { if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below. event.stopPropagation(); if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below. event.preventDefault(); } function globalDatabaseList(cb) { var val, localStorage = Dexie.dependencies.localStorage; if (!localStorage) return cb([]); // Envs without localStorage support try { val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]"); } catch (e) { val = []; } if (cb(val)) { localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val)); } } function awaitIterator (iterator) { var callNext = result => iterator.next(result), doThrow = error => iterator.throw(error), onSuccess = step(callNext), onError = step(doThrow); function step(getNext) { return val => { var next = getNext(val), value = next.value; return next.done ? value : (!value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError)); }; } return step(callNext)(); } // // IndexSpec struct // function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { /// <param name="name" type="String"></param> /// <param name="keyPath" type="String"></param> /// <param name="unique" type="Boolean"></param> /// <param name="multi" type="Boolean"></param> /// <param name="auto" type="Boolean"></param> /// <param name="compound" type="Boolean"></param> /// <param name="dotted" type="Boolean"></param> this.name = name; this.keyPath = keyPath; this.unique = unique; this.multi = multi; this.auto = auto; this.compound = compound; this.dotted = dotted; var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']'); this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; } // // TableSchema struct // function TableSchema(name, primKey, indexes, instanceTemplate) { /// <param name="name" type="String"></param> /// <param name="primKey" type="IndexSpec"></param> /// <param name="indexes" type="Array" elementType="IndexSpec"></param> /// <param name="instanceTemplate" type="Object"></param> this.name = name; this.primKey = primKey || new IndexSpec(); this.indexes = indexes || [new IndexSpec()]; this.instanceTemplate = instanceTemplate; this.mappedClass = null; this.idxByName = arrayToObject(indexes, index => [index.name, index]); } // Used in when defining dependencies later... // (If IndexedDBShim is loaded, prefer it before standard indexedDB) var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {}; function safariMultiStoreFix(storeNames) { return storeNames.length === 1 ? storeNames[0] : storeNames; } function getNativeGetDatabaseNamesFn(indexedDB) { var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); return fn && fn.bind(indexedDB); } // Export Error classes props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; // // Static methods and properties // props(Dexie, { // // Static delete() method. // delete: function (databaseName) { var db = new Dexie(databaseName), promise = db.delete(); promise.onblocked = function (fn) { db.on("blocked", fn); return this; }; return promise; }, // // Static exists() method. // exists: function(name) { return new Dexie(name).open().then(db=>{ db.close(); return true; }).catch(Dexie.NoSuchDatabaseError, () => false); }, // // Static method for retrieving a list of all existing databases at current host. // getDatabaseNames: function (cb) { return new Promise(function (resolve, reject) { var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB); if (getDatabaseNames) { // In case getDatabaseNames() becomes standard, let's prepare to support it: var req = getDatabaseNames(); req.onsuccess = function (event) { resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array<String> }; req.onerror = eventRejectHandler(reject); } else { globalDatabaseList(function (val) { resolve(val); return false; }); } }).then(cb); }, defineClass: function (structure) { /// <summary> /// Create a javascript constructor based on given template for which properties to expect in the class. /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. /// </summary> /// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param> // Default constructor able to copy given properties into this object. function Class(properties) { /// <param name="properties" type="Object" optional="true">Properties to initialize object with. /// </param> properties ? extend(this, properties) : fake && applyStructure(this, structure); } return Class; }, applyStructure: applyStructure, ignoreTransaction: function (scopeFunc) { // In case caller is within a transaction but needs to create a separate transaction. // Example of usage: // // Let's say we have a logger function in our app. Other application-logic should be unaware of the // logger function and not need to include the 'logentries' table in all transaction it performs. // The logging should always be done in a separate transaction and not be dependant on the current // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. // // Dexie.ignoreTransaction(function() { // db.logentries.add(newLogEntry); // }); // // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction // in current Promise-scope. // // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an // API for this because // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). // 3) setImmediate() is not supported in the ES standard. // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. scopeFunc(); // No need to change scope because there is no ongoing transaction. }, vip: function (fn) { // To be used by subscribers to the on('ready') event. // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by // the caller will not resolve until database is opened. return newScope(function () { PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. return fn(); }); }, async: function (generatorFn) { return function () { try { var rv = awaitIterator(generatorFn.apply(this, arguments)); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection (e); } }; }, spawn: function (generatorFn, args, thiz) { try { var rv = awaitIterator(generatorFn.apply(thiz, args || [])); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection(e); } }, // Dexie.currentTransaction property currentTransaction: { get: () => PSD.trans || null }, // Export our Promise implementation since it can be handy as a standalone Promise implementation Promise: Promise, // Dexie.debug proptery: // Dexie.debug = false // Dexie.debug = true // Dexie.debug = "dexie" - don't hide dexie's stack frames. debug: { get: () => debug, set: value => { setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter); } }, // Export our derive/extend/override methodology derive: derive, extend: extend, props: props, override: override, // Export our Events() function - can be handy as a toolkit Events: Events, events: { get: deprecated(()=>Events) }, // Backward compatible lowercase version. // Utilities getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, asap: asap, maxKey: maxKey, // Addon registry addons: [], // Global DB connection list connections: connections, MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate. errnames: errnames, // Export other static classes IndexSpec: IndexSpec, TableSchema: TableSchema, // // Dependencies // // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. // // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). // For node.js, you need to require indexeddb-js or similar and then set these deps. // dependencies: { // Required: indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange }, // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.') .map(n => parseInt(n)) .reduce((p,c,i) => p + (c/Math.pow(10,i*2))), fakeAutoComplete: fakeAutoComplete, // https://github.com/dfahlander/Dexie.js/issues/186 // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return // x.default. Workaround: Set Dexie.default = Dexie. default: Dexie }); tryCatch(()=>{ // Optional dependencies // localStorage Dexie.dependencies.localStorage = ((typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage); }); // Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. Promise.rejectionMapper = mapError; // Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. doFakeAutoComplete(function() { Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; Dexie.fake = fake = true; }); export default Dexie; //# sourceMappingURL=dexie.es6.js.map
client/reader/full-post/controller.js
tinkertinker/wp-calypso
/** * External Dependencies */ import React from 'react'; import ReactDom from 'react-dom'; import { Provider as ReduxProvider } from 'react-redux'; import i18n from 'i18n-calypso'; import page from 'page'; import { defer } from 'lodash'; /** * Internal Dependencies */ import FeedError from 'reader/feed-error'; import { setPageTitle, trackPageLoad } from 'reader/controller-helper'; import { getTitle } from 'state/document-head/selectors'; import { setDocumentHeadTitle as setTitle } from 'state/document-head/actions'; import FullPostDialog from './main'; import ReaderFullPost from 'blocks/reader-full-post'; import { renderWithReduxStore } from 'lib/react-helpers'; const analyticsPageTitle = 'Reader'; // This holds the last title set on the page. Removing the overlay doesn't trigger a re-render, so we need a way to // reset it let __lastTitle = null; function renderPostNotFound() { const sidebarAndPageTitle = i18n.translate( 'Post not found' ); setPageTitle( context, sidebarAndPageTitle ); renderWithReduxStore( <FeedError sidebarTitle={ sidebarAndPageTitle } message={ i18n.translate( 'Post Not Found' ) } />, document.getElementById( 'primary' ), context.store ); } function removeFullPostDialog() { ReactDom.unmountComponentAtNode( document.getElementById( 'tertiary' ) ); } export function resetTitle( context, next ) { if ( __lastTitle ) { context.store.dispatch( setTitle( __lastTitle ) ); // FIXME: Auto-converted from the Flux setTitle action. Please use <DocumentHead> instead. __lastTitle = null; } next(); } export function blogPost( context ) { const blogId = context.params.blog, postId = context.params.post, basePath = '/read/blogs/:blog_id/posts/:post_id', fullPageTitle = analyticsPageTitle + ' > Blog Post > ' + blogId + ' > ' + postId; __lastTitle = getTitle( context.store.getState() ); trackPageLoad( basePath, fullPageTitle, 'full_post' ); // this will automatically unmount anything that was already mounted // in #tertiary, so we don't have to check the current state ReactDom.render( React.createElement( ReduxProvider, { store: context.store }, React.createElement( FullPostDialog, { blogId: blogId, postId: postId, context: context, onClose: function() { page.back( context.lastRoute || '/' ); }, onClosed: removeFullPostDialog, onPostNotFound: renderPostNotFound } ) ), document.getElementById( 'tertiary' ) ); } export function blogPostNew( context ) { var blogId = context.params.blog, postId = context.params.post, basePath = '/read/blogs/:blog_id/posts/:post_id', fullPageTitle = analyticsPageTitle + ' > Blog Post > ' + blogId + ' > ' + postId; __lastTitle = getTitle( context.store.getState() ); trackPageLoad( basePath, fullPageTitle, 'full_post' ); ReactDom.render( React.createElement( ReduxProvider, { store: context.store }, React.createElement( ReaderFullPost, { blogId: blogId, postId: postId, context: context, onClose: function() { page.back( context.lastRoute || '/' ); }, onClosed: removeFullPostDialog, onPostNotFound: renderPostNotFound } ) ), document.getElementById( 'primary' ) ); defer( function() { if ( typeof window !== 'undefined' ) { window.scrollTo( 0, 0 ); } } ); } export function feedPost( context ) { const feedId = context.params.feed, postId = context.params.post, basePath = '/read/feeds/:feed_id/posts/:feed_item_id', fullPageTitle = analyticsPageTitle + ' > Feed Post > ' + feedId + ' > ' + postId; __lastTitle = getTitle( context.store.getState() ); trackPageLoad( basePath, fullPageTitle, 'full_post' ); // this will automatically unmount anything that was already mounted // in #tertiary, so we don't have to check the current state of // __fullPostInstance before making another ReactDom.render( React.createElement( ReduxProvider, { store: context.store }, React.createElement( FullPostDialog, { feedId: feedId, postId: postId, onClose: function() { page.back( context.lastRoute || '/' ); }, onClosed: removeFullPostDialog, onPostNotFound: renderPostNotFound } ) ), document.getElementById( 'tertiary' ) ); } export function feedPostNew( context ) { var feedId = context.params.feed, postId = context.params.post, basePath = '/read/feeds/:feed_id/posts/:feed_item_id', fullPageTitle = analyticsPageTitle + ' > Feed Post > ' + feedId + ' > ' + postId; __lastTitle = getTitle( context.store.getState() ); trackPageLoad( basePath, fullPageTitle, 'full_post' ); function closer() { page.back( context.lastRoute || '/' ); } ReactDom.render( ( <ReduxProvider store={ context.store }> <ReaderFullPost feedId={ feedId } postId={ postId } onClose={ closer } onPostNotFound={ renderPostNotFound } /> </ReduxProvider> ), document.getElementById( 'primary' ) ); defer( function() { if ( typeof window !== 'undefined' ) { window.scrollTo( 0, 0 ); } } ); }
src/Label.js
nickuraltsev/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Label = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render() { let classes = this.getBsClassSet(); return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Label;
app/scripts/Widget/plugins/Match/__tests__/components/AddChoiceForm.spec.js
igr-santos/bonde-client
import React from 'react' import { mount } from 'enzyme' import { expect } from 'chai' import sinon from 'sinon' import { AddChoiceForm } from '../../components/' describe('Match/components/AddChoiceForm', () => { let wrapper let props = { title: undefined, label: undefined, choices: [], handleAddItem: (choice) => {}, handleRemoveItem: (choice) => {}, handleChangeLabel: (label) => {} } beforeEach(() => { wrapper = mount(<AddChoiceForm {...props} />) }) it('should add choices state when clicked add choice', () => { let expected wrapper.setProps({ handleAddItem: (choice) => { expected = choice } }) wrapper.setState({'value': 'teste'}) wrapper.find('button').simulate('click') expect(expected).to.equal('teste') }) it('should remove choices state when clicked remove choice', () => { let expected wrapper.setProps({ choices: ['Item1', 'Item2'], handleRemoveItem: (choice) => { expected = choice } }) const row1 = wrapper.find('.choices-block a').at(0) row1.simulate('click') expect(expected).to.equal('Item1') }) it('should clear input when clicked button', () => { wrapper.setState({ value: 'asdas' }) wrapper.find('button').simulate('click') expect(wrapper.instance().state.value).to.equal('') }) it('should render disabled button add when input empty', () => { wrapper.setState({ value: '' }) const button = wrapper.find('button') expect(button.props().disabled).to.equal(true) }) it('should not add choice when choice exists in list', () => { let expected = undefined wrapper.setProps({ choices: ['Item1'], handleAddItem: (choice) => { expected = choice } }) wrapper.setState({ value: 'Item1' }) wrapper.find('button').simulate('click') expect(expected).to.equal(undefined) }) it('should add choice when keypress [Enter]', () => { let expected wrapper.setProps({ choices: [], handleAddItem: (choice) => { expected = choice } }) wrapper.setState({ value: 'Item1' }) wrapper.find('input').at(1).simulate('keypress', { key: 'Enter' }) expect(expected).to.equal('Item1') }) })
app/index.js
princeV/koa2-react-redux-webpack-boilerplate
import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import Counter from './components/Counter' import counter from './reducers' const store = createStore(counter) const rootEl = document.getElementById('root') const render = () => ReactDOM.render( <Counter value={store.getState()} onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} />, rootEl ) render() store.subscribe(render)
wp-includes/js/jquery/jquery.js
sparshmurali/wordpressnew
/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={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:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.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",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.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",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.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",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},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":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.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){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,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":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m}); jQuery.noConflict();
src/main/resources/js/server.js
maximenajim/isomorphic-javascript-example
import React from "react/addons"; import Page from "./page"; export default function (movies) { var moviesList = Java.from(movies); return React.renderToString( <Page movies={moviesList}/> ); };
scripts/ItemManager.js
krulmacius/sdasdasdasfgasdawsdwadawd
import React from 'react'; import axios from 'axios'; import Alert from 'react-s-alert'; import LazyLoad from 'react-lazyload'; import 'react-s-alert/dist/s-alert-default.css'; import 'react-s-alert/dist/s-alert-css-effects/jelly.css'; class ItemManager extends React.Component { constructor(props) { super(props); this.state = { site_pagination_status: false, site_pagination_count: 0, site_pagination: [], items_per_site: 20, time: 604800, category: 0, site: 1, posts: [] } this.checkPagination = this.checkPagination.bind(this); this.getPagination = this.getPagination.bind(this); this.checkVote = this.checkVote.bind(this); this.getItems = this.getItems.bind(this); this.handleClickTime = this.handleClickTime.bind(this); this.handleClickCategory= this.handleClickCategory.bind(this); this.getButton = this.getButton.bind(this); } componentDidMount() { this.getItems(604800,0, this.state.site); } checkVote(data) { if (data === "fake") return {color: "red"}; else if (data === "legit") return {color: "green"}; else return {color: "#d9d9d9"}; } getItems(time,category,site) { axios.get('itemmanager/items_by_time_and_category?time='+time+'&category='+ category +'&site='+site) .then(res => { const posts = res.data.data; console.log(res); const pagination = this.getPagination(res.data.pagination); if (!res.data) { Alert.error('Brak przedmiotów!', { position: 'top-right', effect: 'jelly' }); this.setState( { site_pagination_status: false } ) } else { if(pagination <= 1) { this.setState( { site_pagination_status: false } ) } else { this.setState( { site_pagination_status: true } ) } } this.setState({ site_pagination_count: res.data.pagination, site: site, site_pagination: pagination, posts: posts, time: time }); }); } checkPagination(name) { var status = ""; if (name === "next") { if (this.state.site === this.state.site_pagination_count) { status = " disabled"; } } if (name === "previous") { if (this.state.site <= 1) { status = " disabled"; } } return ("page-item pagination__item" + status); } getPagination(pagination) { var arr = []; for (var i = 1; i <= pagination; i++) { arr.push(i); } return arr; } handleClickTime(time) { this.setState({ time: time }) this.getItems(time,this.state.category,1); } handleClickCategory(category) { this.setState({ category: category }) this.getItems(this.state.time,category,1); } getButton(category, value, name) { if (category === "time") if (this.state.time == value) return( <a onClick={() => this.handleClickTime(value)} className="btn btn-primary" role="button">{name}</a> ); else return( <a onClick={() => this.handleClickTime(value)} className="btn btn-outline-primary" role="button">{name}</a> ); else if (category === "category") if (this.state.category == value) { var newClass = ""; if (name === "POLECANE") newClass = "btn btn-warning btn-lg my-3 mx-3 col-md-12 col-lg-3"; else if (name === "NAJGORĘTSZE") newClass = "btn btn-danger btn-lg my-3 mx-3 col-md-12 col-lg-3"; else if (name === "NAJNOWSZE") newClass = "btn btn-success btn-lg my-3 mx-3 col-md-12 col-lg-3"; return( <a onClick={() => this.handleClickCategory(value)} className={newClass} role="button">{name}</a> ); } else return( <a onClick={() => this.handleClickCategory(value)} className="btn btn-outline-secondary btn-lg my-3 mx-3 col-md-12 col-lg-3" role="button">{name}</a> ); } render() { return ( <div> <div className="jumbotron jumbotron__homepage jumbotron__homepage--items"> <h3>PRZEDMIOTY</h3> <hr className="my-4" /> {this.getButton("category", 0,"POLECANE")} {this.getButton("category", 1,"NAJGORĘTSZE")} {this.getButton("category", 2,"NAJNOWSZE")} {/* <hr className="my-4" /> */} <p id="buttons-items-time" className="lead"> {this.getButton("time", 3600,"GODZINY")} {this.getButton("time", 86400,"DNIA")} {this.getButton("time", 604800,"TYGODNIA")} </p> </div> <ul className="items"> { (this.state.posts) ? this.state.posts.map((post,id) => <li key={id} className="item__container"> <a className="item__a" href={"przedmiot/" + post.permalink }> <figure className="item_figure"> <LazyLoad height={100}> <img className="item" src={post.url} alt="" /> </LazyLoad> <figcaption> <p className="item_figure__votes" style={this.checkVote(post.word)}> {post.word.toUpperCase() + " " +post.percent + "%"} </p> <p className="item_figure__mark"> {post.mark.toUpperCase()} </p> <p className="item_figure__name"> {post.name} </p> <p className="item_figure__price"> {post.price} PLN </p> </figcaption> </figure> </a> </li> ) : '' } </ul> { (this.state.site_pagination_status) && <ul className="pagination pagination__container justify-content-center"> <li className={this.checkPagination("previous")} > <a className="page-link" style={{paddingRight: 30}} onClick={ () => {this.getItems(this.state.time, this.state.category ,this.state.site-1)}} >Poprzednia</a> </li> { this.state.site_pagination.map(site => <li key={site} className="page-item pagination__item"> <a className="page-link" style={{cursor: "pointer"}} onClick={()=>{ this.getItems(this.state.time, this.state.category ,site) }}>{site}</a> </li> ) } <li className={this.checkPagination("next")} > <a className="page-link" style={{paddingLeft: 30}} onClick={() => {this.getItems(this.state.time, this.state.category ,this.state.site+1)}} >Następna</a> </li> </ul> } </div> ); } } export {ItemManager};
docs/app/Examples/collections/Form/Variations/index.js
koenvg/Semantic-UI-React
import React from 'react' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' const FormFormVariationsExamples = () => ( <ExampleSection title='Form Variations'> <ComponentExample title='Size' description='A form can vary in size.' examplePath='collections/Form/Variations/FormExampleSize' /> <ComponentExample title='Inverted' description='A form on a dark background may have to invert its color scheme.' examplePath='collections/Form/Variations/FormExampleInverted' /> </ExampleSection> ) export default FormFormVariationsExamples
src/components/TopMenu/TopMenu.js
ro-savage/nwa-react-redux-boilerplate
import React from 'react' import { IconButton } from 'react-toolbox/lib/button' import { connect } from 'react-redux' import { toggleMenu } from '../../redux/modules/layout/layout' const TopMenu = (props) => { const handleClick = () => { props.dispatch(toggleMenu()) } return ( <div className="top-menu gridBox" > <IconButton icon="menu" onClick={handleClick} className="burgerMenuBtn" /> <span>Menu Item | Menu Item | Menu Item | Menu Item</span> </div> ) } TopMenu.propTypes = { menuOpen: React.PropTypes.bool, dispatch: React.PropTypes.func.isRequired, } const mapStateToProps = ({ layout }) => ( { menuOpen: layout.menuOpen } ) export default connect(mapStateToProps)(TopMenu)
ajax/libs/clappr/0.0.30/clappr.js
paleozogt/cdnjs
require=(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; 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'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],2:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function assertObject(x) { if (!isObject(x)) throw $TypeError(x + ' is not an Object'); return x; } function setupGlobals(global) { global.Symbol = Symbol; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { assertObject: assertObject, createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, toProperty: toProperty, type: types, typeof: typeOf, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; var toObject = $traceurRuntime.toObject; function spread() { var rv = [], k = 0; for (var i = 0; i < arguments.length; i++) { var valueToSpread = toObject(arguments[i]); for (var j = 0; j < valueToSpread.length; j++) { rv[k++] = valueToSpread[j]; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; } if (superClass === null) return null; throw new $TypeError(); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw new Error(("\"" + action + "\" on closed generator")); case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime.assertObject($traceurRuntime), canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; return this.value_ = this.func.call(global); }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils"; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x | 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function toInteger(x) { x = +x; if (isNaN(x)) return 0; if (!isFinite(x) || x === 0) return x; return x > 0 ? Math.floor(x) : Math.ceil(x); } var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get toInteger() { return toInteger; }, get toLength() { return toLength; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array"; var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__3.toInteger, toLength = $__3.toLength, toObject = $__3.toObject, isCallable = $__3.isCallable; function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } return { get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__5; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator"; var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toObject = $__6.toObject, toUint32 = $__6.toUint32; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__5, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__5), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map"; var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError("Constructor Map requires 'new'"); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError("Map can not be reentrantly initialised"); } initMap(this); if (iterable !== null && iterable !== undefined) { var iter = iterable[Symbol.iterator]; if (iter !== undefined) { for (var $__8 = iterable[Symbol.iterator](), $__9; !($__9 = $__8.next()).done; ) { var $__10 = $traceurRuntime.assertObject($__9.value), key = $__10[0], value = $__10[1]; { this.set(key, value); } } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; } }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0, len = this.entries_.length; i < len; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } } }, {}); return {get Map() { return Map; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object"; var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__11.toInteger, toLength = $__11.toLength, toObject = $__11.toObject, isCallable = $__11.isCallable; var $__11 = $traceurRuntime.assertObject($traceurRuntime), defineProperty = $__11.defineProperty, getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor, getOwnPropertyNames = $__11.getOwnPropertyNames, keys = $__11.keys, privateNames = $__11.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; } }; }); System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap"; var $__default = function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { scheduleFlush(); } }; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 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() { 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; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise"; var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, cast: function(x) { if (x instanceof this) return x; if (isPromise(x)) { var result = getDeferred(this); chain(x, result.resolve, result.reject); return result.promise; } return this.resolve(x); }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } return {get Promise() { return Promise; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String"; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"; var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map; var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")), codePointAt = $__14.codePointAt, contains = $__14.contains, endsWith = $__14.endsWith, fromCodePoint = $__14.fromCodePoint, repeat = $__14.repeat, raw = $__14.raw, startsWith = $__14.startsWith; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")), fill = $__14.fill, find = $__14.find, findIndex = $__14.findIndex; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")), entries = $__14.entries, keys = $__14.keys, values = $__14.values; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")), assign = $__14.assign, is = $__14.is, mixin = $__14.mixin; function maybeDefineMethod(object, name, value) { if (!(name in object)) { Object.defineProperty(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } function polyfillCollections(global) { if (!global.Map) global.Map = Map; } function polyfillString(String) { maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); } function polyfillArray(Array, Symbol) { maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); if (Symbol && Symbol.iterator) { Object.defineProperty(Array.prototype, Symbol.iterator, { value: values, configurable: true, enumerable: false, writable: true }); } } function polyfillObject(Object) { maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } function polyfill(global) { polyfillPromise(global); polyfillCollections(global); polyfillString(global.String); polyfillArray(global.Array, global.Symbol); polyfillObject(global.Object); } polyfill(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfill(global); }; return {}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import"; var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills")); return {}; }); System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + ''); }).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"FWaASH":1}],3:[function(require,module,exports){ /*! * jQuery JavaScript Library v2.1.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:11Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.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( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); },{}],4:[function(require,module,exports){ /** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; },{}],5:[function(require,module,exports){ (function( factory ) { if (typeof define !== 'undefined' && define.amd) { define(['jquery'], factory); } else if (typeof module !== 'undefined' && module.exports) { var $ = require('jquery'); module.exports = factory( $ ); } else { window.scrollMonitor = factory( jQuery ); } })(function( $ ) { var exports = {}; var $window = $(window); var $document = $(document); var watchers = []; var VISIBILITYCHANGE = 'visibilityChange'; var ENTERVIEWPORT = 'enterViewport'; var FULLYENTERVIEWPORT = 'fullyEnterViewport'; var EXITVIEWPORT = 'exitViewport'; var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport'; var LOCATIONCHANGE = 'locationChange'; var STATECHANGE = 'stateChange'; var eventTypes = [ VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE ]; var defaultOffsets = {top: 0, bottom: 0}; exports.viewportTop; exports.viewportBottom; exports.documentHeight; exports.viewportHeight = windowHeight(); var previousDocumentHeight; var latestEvent; function windowHeight() { return window.innerHeight || document.documentElement.clientHeight; } var calculateViewportI; function calculateViewport() { exports.viewportTop = $window.scrollTop(); exports.viewportBottom = exports.viewportTop + exports.viewportHeight; exports.documentHeight = $document.height(); if (exports.documentHeight !== previousDocumentHeight) { calculateViewportI = watchers.length; while( calculateViewportI-- ) { watchers[calculateViewportI].recalculateLocation(); } previousDocumentHeight = exports.documentHeight; } } function recalculateWatchLocationsAndTrigger() { exports.viewportHeight = windowHeight(); calculateViewport(); updateAndTriggerWatchers(); } var recalculateAndTriggerTimer; function debouncedRecalcuateAndTrigger() { clearTimeout(recalculateAndTriggerTimer); recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 ); } var updateAndTriggerWatchersI; function updateAndTriggerWatchers() { // update all watchers then trigger the events so one can rely on another being up to date. updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].update(); } updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].triggerCallbacks(); } } function ElementWatcher( watchItem, offsets ) { var self = this; this.watchItem = watchItem; if (!offsets) { this.offsets = defaultOffsets; } else if (offsets === +offsets) { this.offsets = {top: offsets, bottom: offsets}; } else { this.offsets = $.extend({}, defaultOffsets, offsets); } this.callbacks = {}; // {callback: function, isOne: true } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport; var wasFullyInViewport; var wasAboveViewport; var wasBelowViewport; var listenerToTriggerListI; var listener; function triggerCallbackArray( listeners ) { if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while( listenerToTriggerListI-- ) { listener = listeners[listenerToTriggerListI]; listener.callback.call( self, latestEvent ); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks() { if (this.isInViewport && !wasInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); } if (this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); } switch( true ) { case wasInViewport !== this.isInViewport: case wasFullyInViewport !== this.isFullyInViewport: case wasAboveViewport !== this.isAboveViewport: case wasBelowViewport !== this.isBelowViewport: triggerCallbackArray( this.callbacks[STATECHANGE] ); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function() { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var elementLocation = $(this.watchItem).offset(); this.top = elementLocation.top; this.bottom = elementLocation.top + this.watchItem.offsetHeight; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = exports.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray( this.callbacks[LOCATIONCHANGE] ); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } ElementWatcher.prototype = { on: function( event, callback, isOne ) { // trigger the event if it applies to the element right now. switch( true ) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport: callback(); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({callback: callback, isOne: isOne}); } else { throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, off: function( event, callback ) { if (this.callbacks[event]) { for (var i = 0, item; item = this.callbacks[event][i]; i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, one: function( event, callback ) { this.on( event, callback, true); }, recalculateSize: function() { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; }, update: function() { this.isAboveViewport = this.top < exports.viewportTop; this.isBelowViewport = this.bottom > exports.viewportBottom; this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop); this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); }, destroy: function() { var index = watchers.indexOf(this), self = this; watchers.splice(index, 1); for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]].length = 0; } }, // prevent recalculating the element location lock: function() { this.locked = true; }, unlock: function() { this.locked = false; } }; var eventHandlerFactory = function (type) { return function( callback, isOne ) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; ElementWatcher.prototype[type] = eventHandlerFactory(type); } try { calculateViewport(); } catch (e) { $(calculateViewport); } function scrollMonitorListener(event) { latestEvent = event; calculateViewport(); updateAndTriggerWatchers(); } $window.on('scroll', scrollMonitorListener); $window.on('resize', debouncedRecalcuateAndTrigger); exports.beget = exports.create = function( element, offsets ) { if (typeof element === 'string') { element = $(element)[0]; } if (element instanceof $) { element = element[0]; } var watcher = new ElementWatcher( element, offsets ); watchers.push(watcher); watcher.update(); return watcher; }; exports.update = function() { latestEvent = null; calculateViewport(); updateAndTriggerWatchers(); }; exports.recalculateLocations = function() { exports.documentHeight = 0; exports.update(); }; return exports; }); },{"jquery":3}],6:[function(require,module,exports){ // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); },{}],"base_object":[function(require,module,exports){ module.exports=require('2HNVgz'); },{}],"2HNVgz":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('./events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./events":13,"./utils":23,"underscore":6}],"6xH8xW":[function(require,module,exports){ "use strict"; var BaseObject = require('./base_object'); var ContainerPlugin = function ContainerPlugin(options) { $traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]); this.bindEvents(); }; var $ContainerPlugin = ContainerPlugin; ($traceurRuntime.createClass)(ContainerPlugin, { enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); }, bindEvents: function() {} }, {}, BaseObject); module.exports = ContainerPlugin; },{"./base_object":"2HNVgz"}],"container_plugin":[function(require,module,exports){ module.exports=require('6xH8xW'); },{}],"core_plugin":[function(require,module,exports){ module.exports=require('it+usN'); },{}],"it+usN":[function(require,module,exports){ "use strict"; var BaseObject = require('./base_object'); var CorePlugin = function CorePlugin(core) { $traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]); this.core = core; }; var $CorePlugin = CorePlugin; ($traceurRuntime.createClass)(CorePlugin, {getExternalInterface: function() { return {}; }}, {}, BaseObject); module.exports = CorePlugin; },{"./base_object":"2HNVgz"}],13:[function(require,module,exports){ (function (global){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log'); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; if (global.DEBUG) { if (Log.BLACKLIST.indexOf(name) < 0) Log.info(klass, 'event ' + name + ' triggered'); } if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); module.exports = Events; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../plugins/log":59,"underscore":6}],14:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls> <% var renderBar = function(name) { %> <div class="bar-container" data-<%= name %>> <div class="bar-background" data-<%= name %>> <div class="bar-fill-1" data-<%= name %>></div> <div class="bar-fill-2" data-<%= name %>></div> <div class="bar-hover" data-<%= name %>></div> </div> <div class="bar-scrubber" data-<%= name %>> <div class="bar-scrubber-icon" data-<%= name %>></div> </div> </div> <% }; %> <% var renderDrawer = function(name, renderContent) { %> <div class="drawer-container" data-<%= name %>> <div class="drawer-icon-container" data-<%= name %>> <div class="drawer-icon media-control-icon" data-<%= name %>></div> <span class="drawer-text" data-<%= name %>></span> </div> <% renderContent(name); %> </div> <% }; %> <% var renderIndicator = function(name) { %> <div class="media-control-indicator" data-<%= name %>></div> <% }; %> <% var renderButton = function(name) { %> <button class="media-control-button media-control-icon" data-<%= name %>></button> <% }; %> <% var render = function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.default && settings.default.length) { %> <div class="media-control-center-panel" data-media-control> <% render(settings.default); %> </div> <% } %> <% if (settings.left && settings.left.length) { %> <div class="media-control-left-panel" data-media-control> <% render(settings.left); %> </div> <% } %> <% if (settings.right && settings.right.length) { %> <div class="media-control-right-panel" data-media-control> <% render(settings.right); %> </div> <% } %></div>'), 'seek_time': _.template('<span data-seek-time></span>'), 'flash': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'hls': _.template(' <param name="movie" value="<%= swfPath %>?inline=1"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'), 'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'), 'background_button': _.template('<div class="playpause-button-wrapper" data-background-button> <span class="playpause-icon" data-background-button></span></div>'), 'poster': _.template('<div class="play-wrapper" data-poster> <span class="poster-icon play" data-poster /></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}', 'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}', 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;border-radius:0;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto;max-width:100%;min-width:60%;height:40px;z-index:9999;-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:150px;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:all,.6s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.6s,ease-out;-o-transition:all,.6s,ease-out;transition:all,.6s,ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.5) 0 0 15px;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control].media-control-hide{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-background[data-background],.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:relative;top:10%;height:80%;vertical-align:middle}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:10px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin-right:3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:none;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5)}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:block}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all,.2s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.2s,ease-out;-o-transition:all,.2s,ease-out;transition:all,.2s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}', 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}', 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}', 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.background-button[data-background-button].hide[data-background-button]{opacity:0}.background-button[data-background-button] .playpause-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:20%;top:45%;margin-top:-5%;text-align:center}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]{font-family:Player;cursor:pointer;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;font-size:90px;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]:hover{text-shadow:rgba(255,255,255,.5) 0 0 15px}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].paused:before{content:"\\e001"}', 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;overflow:hidden;width:100%;height:20%;line-height:100%;font-size:20%;top:50%;margin-top:-5%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":6}],"VbgHr3":[function(require,module,exports){ "use strict"; var UIObject = require('../base/ui_object'); var Playback = function Playback(options) { $traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]); this.settings = {}; }; var $Playback = Playback; ($traceurRuntime.createClass)(Playback, { play: function() {}, pause: function() {}, stop: function() {}, seek: function(time) {}, getDuration: function() { return 0; }, isPlaying: function() { return false; }, getPlaybackType: function() { return 'no_op'; }, isHighDefinitionInUse: function() { return false; }, volume: function(value) {}, destroy: function() { this.$el.remove(); } }, {}, UIObject); Playback.canPlay = (function(source) { return false; }); module.exports = Playback; },{"../base/ui_object":22}],"playback":[function(require,module,exports){ module.exports=require('VbgHr3'); },{}],17:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style></style>').html(_.template(JST.CSS[name])(options)); }}; module.exports = Styler; },{"./jst":14,"jquery":3,"underscore":6}],"ui_container_plugin":[function(require,module,exports){ module.exports=require('XSLDWT'); },{}],"XSLDWT":[function(require,module,exports){ "use strict"; var UIObject = require('./ui_object'); var UIContainerPlugin = function UIContainerPlugin(options) { $traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]); this.enabled = true; this.bindEvents(); }; var $UIContainerPlugin = UIContainerPlugin; ($traceurRuntime.createClass)(UIContainerPlugin, { enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, bindEvents: function() {} }, {}, UIObject); module.exports = UIContainerPlugin; },{"./ui_object":22}],"ui_core_plugin":[function(require,module,exports){ module.exports=require('gNZMEo'); },{}],"gNZMEo":[function(require,module,exports){ "use strict"; var UIObject = require('./ui_object'); var UICorePlugin = function UICorePlugin(core) { $traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]); this.core = core; this.enabled = true; this.bindEvents(); this.render(); }; var $UICorePlugin = UICorePlugin; ($traceurRuntime.createClass)(UICorePlugin, { bindEvents: function() {}, getExternalInterface: function() { return {}; }, enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, render: function() { this.$el.html(this.template()); this.$el.append(this.styler.getStyleFor(this.name)); this.core.$el.append(this.el); return this; } }, {}, UIObject); module.exports = UICorePlugin; },{"./ui_object":22}],22:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('./base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var UIObject = function UIObject(options) { $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.cid = _.uniqueId('c'); this._ensureElement(); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./base_object":"2HNVgz","./utils":23,"jquery":3,"underscore":6}],23:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var zeroPad = function(number, size) { return (new Array(size + 1 - number.toString().length)).join('0') + number; }; var formatTime = function(time) { time = time * 1000; time = parseInt(time / 1000); var seconds = time % 60; time = parseInt(time / 60); var minutes = time % 60; time = parseInt(time / 60); var hours = time % 24; var out = ""; if (hours && hours > 0) out += ("0" + hours).slice(-2) + ":"; out += ("0" + minutes).slice(-2) + ":"; out += ("0" + seconds).slice(-2); return out.trim(); }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; var HEX_TAB = "0123456789abcdef"; var B64_TAB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; var b64pad = ""; var rstr2b64 = function(input) { var output = ""; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) output += b64pad; else output += B64_TAB.charAt((triplet >>> 6 * (3 - j)) & 0x3F); } } return output; }; var rstr2hex = function(input) { var output = ""; for (var i = 0; i < input.length; i++) { var x = input.charCodeAt(i); output += HEX_TAB.charAt((x >>> 4) & 0x0F) + HEX_TAB.charAt(x & 0x0F); } return output; }; var getHostname = function() { return location.hostname; }; var Ajax = { jsonp: function(settings) { var defer = new $.Deferred(); settings.callbackName = settings.callbackName || "json_callback"; settings.timeout = settings.timeout || 15000; window[settings.callbackName] = function(data) { if (!Ajax.isErrorObject(data)) { defer.resolve(data); } else { defer.reject(data); } }; var head = $("head")[0]; var script = document.createElement("script"); script.setAttribute("src", settings.url); script.setAttribute("async", "async"); script.onload = script.onreadystatechange = function(eventLoad) { if (!script.readyState || /loaded|complete/.test(script.readyState)) { if (settings.timeoutId) { window.clearTimeout(settings.timeoutId); } script.onload = script.onreadystatechange = null; if (head && script.parentNode) head.removeChild(script); script = undefined; } }; head.insertBefore(script, head.firstChild); if (settings.error) { settings.timeoutId = window.setTimeout(settings.error, settings.timeout); } return defer.promise(); }, isErrorObject: function(data) { return data && data.http_status_code && data.http_status_code != 200; } }; module.exports = { extend: extend, zeroPad: zeroPad, formatTime: formatTime, Fullscreen: Fullscreen, Ajax: Ajax, rstr2b64: rstr2b64, rstr2hex: rstr2hex, getHostname: getHostname }; },{"jquery":3,"underscore":6}],"195Wj5":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i)); Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent)); module.exports = Browser; },{}],"browser":[function(require,module,exports){ module.exports=require('195Wj5'); },{}],26:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Container = function Container(options) { $traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]); this.playback = options.playback; this.settings = this.playback.settings; this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; this.bindEvents(); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return {'data-container': ''}; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.playback, 'playback:progress', this.progress); this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated); this.listenTo(this.playback, 'playback:ready', this.ready); this.listenTo(this.playback, 'playback:buffering', this.buffering); this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull); this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate); this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata); this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged); this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged); this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl); this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl); this.listenTo(this.playback, 'playback:ended', this.ended); this.listenTo(this.playback, 'playback:play', this.playing); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger('container:playbackstate'); }, playbackDvrStateChanged: function(dvrInUse) { this.settings = this.playback.settings; this.trigger('container:dvr', dvrInUse); }, statsAdd: function(metric) { this.trigger('container:stats:add', metric); }, statsReport: function(metrics) { this.trigger('container:stats:report', metrics); }, getPlaybackType: function() { return this.playback.getPlaybackType(); }, destroy: function() { this.trigger('container:destroyed', this, this.name); this.playback.destroy(); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger('container:ready', this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, getDuration: function() { return this.playback.getDuration(); }, error: function(errorObj) { this.trigger('container:error', errorObj, this.name); }, loadedMetadata: function(duration) { this.trigger('container:loadedmetadata', duration); }, timeUpdated: function(position, duration) { this.trigger('container:timeupdate', position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger('container:play', this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger('container:stop', this.name); this.playback.stop(); }, pause: function() { this.trigger('container:pause', this.name); this.playback.pause(); }, ended: function() { this.trigger('container:ended', this, this.name); }, clicked: function() { this.trigger('container:click', this, this.name); }, setCurrentTime: function(time) { this.trigger('container:seek', time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.playback.volume(value); }, requestFullscreen: function() { this.trigger('container:fullscreen', this.name); }, buffering: function() { this.trigger('container:state:buffering', this.name); }, bufferfull: function() { this.trigger('container:state:bufferfull', this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger('container:settingsupdate'); }, highDefinitionUpdate: function() { this.trigger('container:highdefinitionupdate'); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger('container:mediacontrol:disable'); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger('container:mediacontrol:enable'); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); module.exports = Container; },{"../../base/styler":17,"../../base/ui_object":22,"underscore":6}],27:[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":26}],28:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Container = require('../container'); var $ = require('jquery'); var ContainerFactory = function ContainerFactory(options, loader) { $traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]); this.options = options; this.loader = loader; }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { createContainers: function() { return $.Deferred(function(promise) { promise.resolve(_.map(this.options.sources, function(source) { return this.createContainer(source); }, this)); }.bind(this)); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay(source.toString()); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var options = _.extend({}, this.options, { src: source, autoPlay: !!this.options.autoPlay }); var playback = new playbackPlugin(options); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, 'container:ready', (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(Plugin) { var options = _.extend(this.options, { container: container, src: source }); container.addPlugin(new Plugin(options)); }, this); } }, {}, BaseObject); module.exports = ContainerFactory; },{"../../base/base_object":"2HNVgz","../container":27,"jquery":3,"underscore":6}],29:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":28}],30:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var UIObject = require('../../base/ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Styler = require('../../base/styler'); var MediaControl = require('../media_control'); var PlayerInfo = require('../player_info'); var Mediator = require('../mediator'); var Core = function Core(options) { var $__0 = this; $traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]); this.playerInfo = PlayerInfo.getInstance(); this.playerInfo.options = options; this.options = options; this.plugins = []; this.containers = []; this.createContainers(options); this.updateSize(); document.addEventListener('fullscreenchange', (function() { return $__0.exit(); })); document.addEventListener('MSFullscreenChange', (function() { return $__0.exit(); })); document.addEventListener('mozfullscreenchange', (function() { return $__0.exit(); })); $(window).resize((function() { return $__0.updateSize(); })); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, createContainers: function(options) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.containerFactory = new ContainerFactory(options, options.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); this.playerInfo.currentSize = { width: window.innerWidth, height: window.innerHeight }; } else { var needStretch = !!this.options.stretchWidth && !!this.options.stretchHeight; var width, height; if (needStretch && this.options.stretchWidth <= window.innerWidth && this.options.stretchHeight <= (window.innerHeight * 0.73)) { width = this.options.stretchWidth; height = this.options.stretchHeight; } else { width = this.options.width; height = this.options.height; } this.$el.css({width: width}); this.$el.css({height: height}); this.$el.removeClass('fullscreen'); this.playerInfo.currentSize = { width: width, height: height }; } Mediator.trigger('player:resize'); }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isString(sources) ? [sources] : sources; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.options = _(this.options).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); this.$el.remove(); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.options.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options)); this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false)); } }, createMediaControl: function(options) { if (options.mediacontrol && options.mediacontrol.external) { return new options.mediacontrol.external(options); } else { return new MediaControl(options); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var $__0 = this; var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.$el.ready((function() { $__0.options.width = $__0.options.width || $__0.$el.width(); $__0.options.height = $__0.options.height || $__0.$el.height(); $__0.updateSize(); })); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23,"../container_factory":29,"../media_control":"A8Uh+k","../mediator":"veeMMc","../player_info":"Pce0iO","jquery":3,"underscore":6}],31:[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":30}],32:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Core = require('../core'); var CoreFactory = function CoreFactory(player, loader) { this.player = player; this.options = player.options; this.loader = loader; this.options.loader = this.loader; }; ($traceurRuntime.createClass)(CoreFactory, { create: function() { this.core = new Core(this.options); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.corePlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }, {}, BaseObject); module.exports = CoreFactory; },{"../../base/base_object":"2HNVgz","../core":31,"underscore":6}],33:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":32}],34:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":35}],35:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var _ = require('underscore'); var PlayerInfo = require('../player_info'); var HTML5VideoPlayback = require('../../playbacks/html5_video'); var FlashVideoPlayback = require('../../playbacks/flash'); var HTML5AudioPlayback = require('../../playbacks/html5_audio'); var HLSVideoPlayback = require('../../playbacks/hls'); var NoOp = require('../../playbacks/no_op'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('../../plugins/poster'); var BackgroundButton = require('../../plugins/background_button'); var Loader = function Loader(externalPlugins) { $traceurRuntime.superCall(this, $Loader.prototype, "constructor", []); this.playerInfo = PlayerInfo.getInstance(); this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin]; this.corePlugins = [BackgroundButton]; if (externalPlugins) { this.addExternalPlugins(externalPlugins); } }; var $Loader = Loader; ($traceurRuntime.createClass)(Loader, { addExternalPlugins: function(plugins) { var pluginName = function(plugin) { return plugin.prototype.name; }; if (plugins.playback) { this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName); } if (plugins.container) { this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName); } if (plugins.core) { this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName); } this.playerInfo.playbackPlugins = this.playbackPlugins; }, getPlugin: function(name) { var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins); return _.find(allPlugins, function(plugin) { return plugin.prototype.name === name; }); } }, {}, BaseObject); module.exports = Loader; },{"../../base/base_object":"2HNVgz","../../playbacks/flash":48,"../../playbacks/hls":50,"../../playbacks/html5_audio":52,"../../playbacks/html5_video":54,"../../playbacks/no_op":55,"../../plugins/background_button":58,"../../plugins/poster":61,"../../plugins/spinner_three_bounce":63,"../../plugins/stats":65,"../../plugins/watermark":67,"../player_info":"Pce0iO","underscore":6}],"A8Uh+k":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":38}],"media_control":[function(require,module,exports){ module.exports=require('A8Uh+k'); },{}],38:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('../../base/ui_object'); var Utils = require('../../base/utils'); var Mousetrap = require('mousetrap'); var SeekTime = require('../seek_time'); var transitionEvents = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'; var MediaControl = function MediaControl(options) { var $__0 = this; $traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]); this.seekTime = new SeekTime(this); this.options = options; this.currentVolume = this.options.mute ? 0 : 100; this.container = options.container; this.container.setVolume(this.currentVolume); this.keepVisible = false; this.addEventListeners(); this.settings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.disabled = false; if (this.container.mediaControlDisabled || this.options.chromeless) { this.disable(); } $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click [data-seekbar]': 'seek', 'click .bar-background[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseover .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mouseenter .bar-container[data-volume]': 'mousemoveOnSeekBar', 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar', 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, addEventListeners: function() { this.listenTo(this.container, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, 'container:ended', this.ended); }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.options.chromeless) return; this.disabled = false; this.show(); }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); this.trigger('mediacontrol:playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger('mediacontrol:notplaying'); } }, mousemoveOnSeekBar: function(event) { if (this.container.settings.seekEnabled) { var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2); this.$seekBarHover.css({left: offsetX}); this.$seekBarHover.show(); } this.trigger('mediacontrol:mousemove:seekbar', event); }, mouseleaveOnSeekBar: function(event) { this.$seekBarHover.hide(); this.trigger('mediacontrol:mouseleave:seekbar', event); }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { if (!this.container.settings.seekEnabled) return; this.draggingSeekBar = true; this.$seekBarLoaded.addClass('media-control-notransition'); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.$seekBarLoaded.removeClass('media-control-notransition'); this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageY - this.$volumeBarContainer.offset().top; this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100; this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); }, toggleMute: function() { if (!!this.mute) { this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); this.mute = false; } else { this.container.setVolume(0); this.setVolumeLevel(0); this.mute = true; } }, toggleFullscreen: function() { this.trigger('mediacontrol:fullscreen', this.name); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) { this.disable(); } this.trigger("mediacontrol:containerchanged"); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.show(); this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; if (!this.$volumeBarContainer) return; if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { $__0.$volumeBarContainer.one(transitionEvents, (function() { $__0.$volumeBarContainer.off(transitionEvents); $__0.$volumeBarContainer.hide(); })); $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), 750); }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; if (position < 0) position = duration; this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { if (!this.container.settings.seekEnabled) return; var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, isVisible: function() { return !this.$el.hasClass('media-control-hide'); }, show: function(event) { var $__0 = this; if (this.disabled || this.isVisible()) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { if (this.hideId) { clearTimeout(this.hideId); } this.$el.show(); this.trigger('mediacontrol:show', this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; if (this.hideId) { clearTimeout(this.hideId); } if (!this.isVisible()) return; if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { if (this.$volumeBarContainer) { this.$volumeBarContainer.hide(); } this.trigger('mediacontrol:hide', this.name); this.$el.addClass('media-control-hide'); } }, settingsUpdate: function() { this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.render(); }, highDefinitionUpdate: function() { if (this.container.isHighDefinitionInUse()) { this.$el.find('button[data-hd-indicator]').addClass("enabled"); } else { this.$el.find('button[data-hd-indicator]').removeClass("enabled"); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]'); this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]'); this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var $__0 = this; if (!this.container.isReady) { this.listenToOnce(this.container, "container:ready", (function() { return $__0.setVolumeLevel(value); })); } else { var containerHeight = this.$volumeBarContainer.height(); var barHeight = this.$volumeBarBackground.height(); var offset = (containerHeight - barHeight) / 2.0; var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset; this.$volumeBarFill.css({height: value + '%'}); this.$volumeBarScrubber.css({bottom: pos}); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } } }, setSeekPercentage: function(value) { if (value > 100) return; var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0); this.currentSeekPercentage = value; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; Mousetrap.bind(['space'], (function() { return $__0.togglePlayPause(); })); }, parseColors: function() { var $__0 = this; var translate = { query: { 'seekbar': '.bar-fill-2[data-seekbar]', 'buttons': '[data-media-control] > .media-control-icon, [data-volume]' }, rule: { 'seekbar': 'background-color', 'buttons': 'color' } }; var customColors = _.pick(this.options.mediacontrol, 'seekbar', 'buttons'); _.each(customColors, (function(value, key) { $__0.$el.find(translate.query[key]).css(translate.rule[key], customColors[key]); })); }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); this.$el.html(this.template({settings: this.settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.$volumeBarContainer.hide(); this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) { this.hide(); } this.$seekBarHover.hide(); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (!this.currentSeekPercentage) { this.currentSeekPercentage = 0; } this.setSeekPercentage(this.currentSeekPercentage); this.$el.ready((function() { if (!$__0.container.settings.seekEnabled) { $__0.$seekBarContainer.addClass('seek-disabled'); } $__0.setVolumeLevel($__0.currentVolume); $__0.bindKeyEvents(); })); this.parseColors(); this.seekTime.render(); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23,"../seek_time":44,"jquery":3,"mousetrap":4,"underscore":6}],"veeMMc":[function(require,module,exports){ "use strict"; var Events = require('../base/events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"../base/events":13}],"mediator":[function(require,module,exports){ module.exports=require('veeMMc'); },{}],"Pce0iO":[function(require,module,exports){ "use strict"; module.exports = require('./player_info'); },{"./player_info":43}],"player_info":[function(require,module,exports){ module.exports=require('Pce0iO'); },{}],43:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var PlayerInfo = function PlayerInfo() { this.options = {}; this.playbackPlugins = []; this.currentSize = { width: 0, height: 0 }; }; ($traceurRuntime.createClass)(PlayerInfo, {}, {}, BaseObject); PlayerInfo.getInstance = function() { if (this._instance === undefined) { this._instance = new this(); } return this._instance; }; module.exports = PlayerInfo; },{"../../base/base_object":"2HNVgz"}],44:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":45}],45:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var formatTime = require('../../base/utils').formatTime; var SeekTime = function SeekTime(mediaControl) { $traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []); this.mediaControl = mediaControl; this.addEventListeners(); }; var $SeekTime = SeekTime; ($traceurRuntime.createClass)(SeekTime, { get name() { return 'seek_time'; }, get template() { return JST.seek_time; }, get attributes() { return { 'class': 'seek-time hidden', 'data-seek-time': '' }; }, addEventListeners: function() { this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime); this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime); }, showTime: function(event) { var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left; var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0)); var pointerPosition = offset - (this.$el.width() / 2); var currentTime = timePosition * this.mediaControl.container.getDuration() / 100; var options = { timestamp: currentTime, formattedTime: formatTime(currentTime), pointerPosition: pointerPosition }; this.update(options); }, hideTime: function() { this.$el.addClass('hidden'); }, update: function(options) { if (this.mediaControl.container.getPlaybackType() === 'vod') { this.$el.find('[data-seek-time]').text(options.formattedTime); this.$el.css('left', options.pointerPosition); this.$el.removeClass('hidden'); } }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.mediaControl.$el.append(this.el); } }, {}, UIObject); module.exports = SeekTime; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../base/utils":23}],46:[function(require,module,exports){ (function (global){ "use strict"; var BaseObject = require('./base/base_object'); var CoreFactory = require('./components/core_factory'); var Loader = require('./components/loader'); var Mediator = require('./components/mediator'); var _ = require('underscore'); var ScrollMonitor = require('scrollmonitor'); var PlayerInfo = require('./components/player_info'); var Player = function Player(options) { $traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]); window.p = this; this.options = options; this.options.sources = this.normalizeSources(options); this.loader = new Loader(this.options.plugins || []); this.coreFactory = new CoreFactory(this, this.loader); this.playerInfo = PlayerInfo.getInstance(); options.height || (options.height = 360); options.width || (options.width = 640); this.playerInfo.currentSize = { width: options.width, height: options.height }; }; var $Player = Player; ($traceurRuntime.createClass)(Player, { attachTo: function(element) { this.options.parentElement = element; this.core = this.coreFactory.create(); if (this.options.autoPlayVisible) { this.bindAutoPlayVisible(this.options.autoPlayVisible); } }, bindAutoPlayVisible: function(option) { var $__0 = this; this.elementWatcher = ScrollMonitor.create(this.core.$el); if (option === 'full') { this.elementWatcher.fullyEnterViewport((function() { return $__0.enterViewport(); })); } else if (option === 'partial') { this.elementWatcher.enterViewport((function() { return $__0.enterViewport(); })); } }, enterViewport: function() { if (this.elementWatcher.top !== 0 && !this.isPlaying()) { this.play(); } }, normalizeSources: function(options) { return _.compact(_.flatten([options.source, options.sources])); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); }, play: function() { this.core.mediaControl.container.play(); }, pause: function() { this.core.mediaControl.container.pause(); }, stop: function() { this.core.mediaControl.container.stop(); }, seek: function(time) { this.core.mediaControl.container.setCurrentTime(time); }, setVolume: function(volume) { this.core.mediaControl.container.setVolume(volume); }, mute: function() { this.core.mediaControl.container.setVolume(0); }, unmute: function() { this.core.mediaControl.container.setVolume(100); }, isPlaying: function() { return this.core.mediaControl.container.isPlaying(); } }, {}, BaseObject); global.DEBUG = false; window.Clappr = { Player: Player, Mediator: Mediator }; module.exports = window.Clappr; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./base/base_object":"2HNVgz","./components/core_factory":33,"./components/loader":34,"./components/mediator":"veeMMc","./components/player_info":"Pce0iO","scrollmonitor":5,"underscore":6}],47:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var _ = require('underscore'); var $ = require('jquery'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var Flash = function Flash(options) { $traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]); this.src = options.src; this.isRTMP = (this.src.indexOf("rtmp") > -1); this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf"; this.autoPlay = options.autoPlay; this.settings = {default: ['seekbar']}; if (this.isRTMP) { this.settings.left = ["playstop", "volume"]; this.settings.right = ["fullscreen"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["volume", "fullscreen"]; this.settings.seekEnabled = true; } this.isReady = false; this.addListeners(); }; var $Flash = Flash; ($traceurRuntime.createClass)(Flash, { get name() { return 'flash'; }, get tagName() { return 'object'; }, get template() { return JST.flash; }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; if (this.currentState === 'PLAYING') { this.firstPlay(); } else { this.currentState = "IDLE"; this.autoPlay && this.play(); } $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); this.trigger('playback:ready', this.name); }, getPlaybackType: function() { return this.isRTMP ? 'live' : 'vod'; }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash', ''); this.setElement($el[0]); }, isHighDefinitionInUse: function() { return false; }, updateTime: function() { this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name); }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':progress', (function() { return $__0.progress(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':statechanged', (function() { return $__0.checkState(); })); Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); }, checkState: function() { if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") { this.trigger('playback:buffering', this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger('playback:bufferfull', this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name); } }, firstPlay: function() { this.currentState = "PLAYING"; if (_.isFunction(this.el.playerPlay)) { this.el.playerPlay(this.src); } }, play: function() { if (this.el.getState() === 'PAUSED') { this.currentState = "PLAYING"; this.el.playerResume(); } else if (this.el.getState() !== 'PLAYING') { this.firstPlay(); } this.trigger('playback:play', this.name); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.playerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { return !!(this.isReady && this.currentState === "PLAYING"); }, getDuration: function() { return this.el.getDuration(); }, seek: function(time) { var seekTo = this.el.getDuration() * (time / 100); this.el.playerSeek(seekTo); this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name); if (this.currentState === "PAUSED") { this.pause(); } }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } this.$el.append(style); return this; } }, {}, UIObject); Flash.canPlay = function(resource) { if (resource.indexOf('rtmp') > -1) { return true; } else if (Browser.isFirefox || Browser.isLegacyIE) { return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/); } }; module.exports = Flash; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_object":22,"../../components/browser":"195Wj5","../../components/mediator":"veeMMc","jquery":3,"underscore":6}],48:[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":47}],49:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('../../components/mediator'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var HLS = function HLS(options) { $traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]); this.src = options.src; this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf"; this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop"], default: ['seekbar'], right: ["fullscreen", "volume", "hd-indicator"], seekEnabled: true }; this.settings = _.extend({}, this.defaultSettings); this.addListeners(); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'class': 'hls-playback', 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':playbackstate', (function(state) { return $__0.setPlaybackState(state); })); Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) { return $__0.updateHighDefinition(isHD); })); Mediator.on(this.uniqueId + ':playbackerror', (function() { return $__0.flashPlaybackError(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); Mediator.off(this.uniqueId + ':playbackerror'); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.el.globoPlayerSetflushLiveURLCache(true); this.autoPlay && this.play(); }, updateHighDefinition: function(isHD) { this.highDefinition = (isHD === "true"); this.trigger('playback:highdefinitionupdate'); }, updateTime: function() { var duration = this.getDuration(); var position = this.el.globoGetPosition(); var livePlayback = this.playbackType === 'live'; if (livePlayback && (position >= duration || position < 0)) { position = duration; } var previousDVRStatus = this.dvrEnabled; this.dvrEnabled = (livePlayback && duration > 240); if (this.dvrEnabled !== previousDVRStatus) { this.updateSettings(); this.trigger('playback:settingsupdate', this.name); } if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) { position = duration; } this.trigger('playback:timeupdate', position, duration, this.name); }, play: function() { if (this.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else if (this.currentState !== "PLAYING") { this.firstPlay(); } this.trigger('playback:play', this.name); }, getPlaybackType: function() { if (this.playbackType) return this.playbackType; return null; }, getCurrentBitrate: function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinitionInUse: function() { return this.highDefinition; }, getLevels: function() { if (!this.levels || this.levels.length === 0) { this.levels = this.el.globoGetLevels(); } return this.levels; }, setPlaybackState: function(state) { var bufferLength = this.el.globoGetbufferLength(); if (state === "PLAYING_BUFFERING" && bufferLength < 1) { this.trigger('playback:buffering', this.name); this.updateCurrentState(state); } else if (state === "PLAYING") { if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) { this.trigger('playback:bufferfull', this.name); this.updateCurrentState(state); } } else if (state === "PAUSED") { this.updateCurrentState(state); } else if (state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name); this.updateCurrentState(state); } this.lastBufferLength = bufferLength; }, updateCurrentState: function(state) { this.currentState = state; this.updatePlaybackType(); }, updatePlaybackType: function() { this.playbackType = this.el.globoGetType(); if (this.playbackType) { this.playbackType = this.playbackType.toLowerCase(); } this.trigger('playback:playbackstate'); }, firstPlay: function() { this.el.globoPlayerLoad(this.src); this.el.globoPlayerPlay(); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.globoPlayerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { if (this.playbackType !== 'live' || this.dvrEnabled) { this.el.globoPlayerPause(); if (this.playbackType === 'live' && this.dvrEnabled) { this.updateDvr(true); } } }, stop: function() { this.el.globoPlayerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { if (this.currentState) { return !!(this.currentState.match(/playing/i)); } return false; }, getDuration: function() { var duration = this.el.globoGetDuration(); if (this.playbackType === 'live') { duration = duration - 10; } return duration; }, seek: function(time) { var duration = this.getDuration(); if (time > 0) { time = duration * time / 100; } if (this.playbackType === 'live') { var dvrInUse = (duration - time > 5); if (!dvrInUse) { time = -1; } this.updateDvr(dvrInUse); } this.el.globoPlayerSeek(time); this.trigger('playback:timeupdate', time, duration, this.name); }, updateDvr: function(dvrInUse) { var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = dvrInUse; if (this.dvrInUse !== previousDvrInUse) { this.updateSettings(); this.trigger('playback:dvr', this.dvrInUse); this.trigger('playback:stats:add', {'dvr': this.dvrInUse}); } }, flashPlaybackError: function() { this.trigger('playback:stop'); }, timeUpdate: function(time, duration) { this.trigger('playback:timeupdate', time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrInUse) { this.settings.left = ["playpause", "position", "duration"]; } else if (this.dvrEnabled) { this.settings.left = ["playpause"]; } else { this.settings.seekEnabled = false; } }, setElement: function(element) { this.$el = element; this.el = element[0]; }, render: function() { var style = Styler.getStyleFor(this.name); if (Browser.isLegacyIE) { this.setupIE(); } else { this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isIE) { this.$('embed').remove(); } } this.el.id = this.cid; this.$el.append(style); return this; } }, {}, Playback); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8/); }; module.exports = HLS; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","../../components/mediator":"veeMMc","underscore":6}],50:[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":49}],51:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var HTML5Audio = function HTML5Audio(params) { $traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]); this.el.src = params.src; this.settings = { left: ['playpause', 'position', 'duration'], right: ['fullscreen', 'volume'], default: ['seekbar'] }; this.render(); params.autoPlay && this.play(); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended' }; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, getPlaybackType: function() { return "aod"; }, play: function() { this.el.play(); this.trigger('playback:play'); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger('container:timeupdate', 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, timeUpdated: function() { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); }, render: function() { return this; } }, {}, Playback); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"../../base/playback":"VbgHr3"}],52:[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":51}],53:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Browser = require('../../components/browser'); var _ = require('underscore'); var HTML5Video = function HTML5Video(options) { $traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]); this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.isHLS = (this.src.indexOf('m3u8') > -1); this.settings = {default: ['seekbar']}; if (this.isHLS) { this.settings.left = ["playstop"]; this.settings.right = ["fullscreen", "volume"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get tagName() { return 'video'; }, get template() { return JST.html5_video; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'playing': 'playing', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, loadedMetadata: function(e) { this.trigger('playback:loadedmetadata', e.target.duration); this.trigger('playback:settingsupdate'); }, getPlaybackType: function() { return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'; }, isHighDefinitionInUse: function() { return false; }, play: function() { this.el.play(); this.trigger('playback:play'); if (this.isHLS) { this.trigger('playback:timeupdate', 1, 1, this.name); } }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod') { this.trigger('playback:buffering', this.name); } }, waiting: function() { this.trigger('playback:buffering', this.name); }, bufferFull: function() { this.trigger('playback:bufferfull', this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { if (this.getPlaybackType() !== 'live') { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); } }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, typeFor: function(src) { return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) })); this.$el.append(style); this.trigger('playback:ready', this.name); this.options.autoPlay && this.play(); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App); }; module.exports = HTML5Video; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5","underscore":6}],54:[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":53}],55:[function(require,module,exports){ "use strict"; module.exports = require('./no_op'); },{"./no_op":56}],56:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var NoOp = function NoOp(options) { $traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]); }; var $NoOp = NoOp; ($traceurRuntime.createClass)(NoOp, { get name() { return 'no_op'; }, get template() { return JST.no_op; }, get attributes() { return {'data-no-op': ''}; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); return this; } }, {}, Playback); NoOp.canPlay = (function(source) { return true; }); module.exports = NoOp; },{"../../base/jst":14,"../../base/playback":"VbgHr3","../../base/styler":17}],57:[function(require,module,exports){ "use strict"; var UICorePlugin = require('../../base/ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var BackgroundButton = function BackgroundButton(core) { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $BackgroundButton = BackgroundButton; ($traceurRuntime.createClass)(BackgroundButton, { get template() { return JST.background_button; }, get name() { return 'background_button'; }, get events() { return {'click .playpause-icon': 'click'}; }, get attributes() { return { 'class': 'background-button', 'data-background-button': '' }; }, bindEvents: function() { this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide); this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.show); this.listenTo(this.core.mediaControl, 'mediacontrol:hide', this.hide); this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing); this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying); }, settingsUpdate: function() { this.stopListening(); if (this.shouldRender()) { this.render(); this.bindEvents(); if (this.core.mediaControl.container.isPlaying()) { this.playing(); } else { this.notplaying(); } } else { this.hide(); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); } }, shouldRender: function() { var settings = this.core.mediaControl.settings; var useBackgroundButton = this.core.options.useBackgroundButton === undefined || !!this.core.options.useBackgroundButton; return useBackgroundButton && (settings.default.indexOf('playpause') >= 0 || settings.left.indexOf('playpause') >= 0 || settings.right.indexOf('playpause') >= 0); }, click: function() { this.core.mediaControl.togglePlayPause(); }, show: function() { this.$el.removeClass('hide'); }, hide: function() { this.$el.addClass('hide'); }, enable: function() { this.stopListening(); $traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []); this.core.mediaControl.$el.find('[data-playpause]').hide(); }, disable: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []); this.core.mediaControl.$el.find('[data-playpause]').show(); }, playing: function() { this.$el.find('.playpause-icon[data-background-button]').removeClass('paused').addClass('playing'); }, notplaying: function() { this.$el.find('.playpause-icon[data-background-button]').removeClass('playing').addClass('paused'); }, getExternalInterface: function() {}, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); if (this.enabled) { this.core.mediaControl.$el.find('[data-playpause]').hide(); } this.core.$el.append(this.$el); if (this.core.mediaControl.isVisible()) { this.show(); } return this; } }, {}, UICorePlugin); module.exports = BackgroundButton; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_core_plugin":"gNZMEo"}],58:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":57}],59:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":60}],60:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var BOLD = 'font-weight: bold; font-size: 13px;'; var INFO = 'color: green;' + BOLD; var DEBUG = 'color: #222;' + BOLD; var ERROR = 'color: red;' + BOLD; var DEFAULT = ''; $(document).keydown(function(e) { if (e.ctrlKey && e.shiftKey && e.keyCode === 68) { window.DEBUG = !window.DEBUG; } }); var Log = function(klass) { this.klass = klass || 'Logger'; }; Log.info = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.error = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; Log.prototype = { log: function(msg) { this.info(msg); }, info: function(msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg); }, error: function(msg) { console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg); } }; module.exports = Log; },{"jquery":3}],61:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":62}],62:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var PlayerInfo = require('../../components/player_info'); var $ = require('jquery'); var _ = require('underscore'); var PosterPlugin = function PosterPlugin(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]); this.options = options; _.defaults(this.options, {disableControlsOnPoster: true}); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } this.render(); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { var $__0 = this; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); Mediator.on('player:resize', (function() { return $__0.updateSize(); })); }, onBuffering: function() { this.hidePlayButton(); }, onPlay: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.updateSize(); this.$playButton.show(); }, clicked: function() { this.container.play(); }, updateSize: function() { if (!this.$el) return; var playerInfo = PlayerInfo.getInstance(); var height = playerInfo.currentSize ? playerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.container.$el.append(this.el); this.$el.ready((function() { return $__0.updateSize(); })); this.$playButton = $(this.$el.find('.play-wrapper')); if (this.options.poster !== undefined) { var imgEl = $('<img data-poster class="poster-background"></img>'); imgEl.attr('src', this.options.poster); this.$el.prepend(imgEl); } return this; } }, {}, UIContainerPlugin); module.exports = PosterPlugin; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT","../../components/mediator":"veeMMc","../../components/player_info":"Pce0iO","jquery":3,"underscore":6}],63:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":64}],64:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST.spinner_three_bounce; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stop', this.onStop); this.render(); }; var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin; ($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, { get name() { return 'spinner'; }, get attributes() { return { 'data-spinner': '', 'class': 'spinner-three-bounce' }; }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.html(this.template()); var style = Styler.getStyleFor('spinner_three_bounce'); this.container.$el.append(style); this.container.$el.append(this.$el); this.$el.hide(); return this; } }, {}, UIContainerPlugin); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}],65:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":66}],66:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('../../base/container_plugin'); var $ = require("jquery"); var StatsPlugin = function StatsPlugin(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, bindEvents: function() { this.listenTo(this.container.playback, 'playback:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd); }, setReportInterval: function(reportInterval) { this.reportInterval = reportInterval; }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); if (!this.intervalId) { this.intervalId = setInterval(this.report.bind(this), this.reportInterval); } }, onStop: function() { clearInterval(this.intervalId); this.intervalId = undefined; this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else if (!!this.rebufferingTimeInit) { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { var stats = this.getStats(); this.container.statsReport(this.getStats()); } }, {}, ContainerPlugin); module.exports = StatsPlugin; },{"../../base/container_plugin":"6xH8xW","jquery":3}],67:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":68}],68:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('../../base/ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var WaterMarkPlugin = function WaterMarkPlugin(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; if (options.watermark) { this.imageUrl = options.watermark; this.render(); } else { this.$el.remove(); } }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIContainerPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":14,"../../base/styler":17,"../../base/ui_container_plugin":"XSLDWT"}]},{},[2,46])
src/js/pages/Proposals/Edit/BasicPage.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import translate from '../../../i18n/Translate'; import AuthenticatedComponent from "../../../components/AuthenticatedComponent"; import connectToStores from "../../../utils/connectToStores"; import TopNavBar from '../../../components/TopNavBar/TopNavBar.js'; import StepsBar from "../../../components/ui/StepsBar/StepsBar"; import Input from "../../../components/ui/Input/Input"; import Textarea from "../../../components/ui/Textarea/Textarea"; import CreatingProposalStore from '../../../stores/CreatingProposalStore'; import * as ProposalActionCreators from "../../../actions/ProposalActionCreators"; import SelectInline from "../../../components/ui/SelectInline/SelectInline"; import ProposalStore from "../../../stores/ProposalStore"; import '../../../../scss/pages/proposals/edit/basic-page.scss'; /** * Requests data from server (or store) for current props. */ function requestData() { ProposalActionCreators.requestOwnProposals(); } /** * Retrieves state from stores for current props. */ function getState(props) { const proposalId = props.params.proposalId; let proposal; if (proposalId) { proposal = ProposalStore.getOwnProposal(proposalId); if (proposal) { CreatingProposalStore.proposal.id = proposal.id; CreatingProposalStore.proposal.type = proposal.type; CreatingProposalStore.proposal.filters = proposal.filters; CreatingProposalStore.proposal.fields = proposal.fields; } } else { proposal = {}; if (!CreatingProposalStore.proposal.fields.title) CreatingProposalStore.proposal.fields.title = ""; if (!CreatingProposalStore.proposal.fields.description) CreatingProposalStore.proposal.fields.description = ""; if (!CreatingProposalStore.proposal.filters) CreatingProposalStore.proposal.filters = {}; if (!CreatingProposalStore.proposal.type) CreatingProposalStore.proposal.type = ""; } return { proposal, }; } @AuthenticatedComponent @translate('ProposalBasicEditPage') @connectToStores([ProposalStore, CreatingProposalStore], getState) export default class ProposalBasicEditPage extends Component { static propTypes = { params : PropTypes.shape({ proposalId: PropTypes.string }).isRequired, // Injected by @AuthenticatedComponent user : PropTypes.object.isRequired, // Injected by @translate: strings : PropTypes.object, // Injected by @connectToStores: proposal : PropTypes.object, }; static contextTypes = { router : PropTypes.object.isRequired }; constructor(props) { super(props); this.state = { type : '', title : '', description : '', }; this.topNavBarLeftLinkClick = this.topNavBarLeftLinkClick.bind(this); this.topNavBarRightLinkClick = this.topNavBarRightLinkClick.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.handleDescriptionChange = this.handleDescriptionChange.bind(this); this.handleSelectInlineClick = this.handleSelectInlineClick.bind(this); this.handleStepsBarClick = this.handleStepsBarClick.bind(this); } componentDidMount() { requestData(this.props); } // componentWillMount() { // if (CreatingProposalStore.proposal.fields) { // if (CreatingProposalStore.proposal.type) { // this.setState({ // type : CreatingProposalStore.proposal.type, // }); // } // if (CreatingProposalStore.proposal.fields.title) { // this.setState({ // title : CreatingProposalStore.proposal.fields.title, // }); // } // if (CreatingProposalStore.proposal.fields.description) { // this.setState({ // description : CreatingProposalStore.proposal.fields.description, // }); // } // } // } topNavBarLeftLinkClick() { ProposalActionCreators.cleanCreatingProposal(); this.context.router.goBack(); } topNavBarRightLinkClick() { ProposalActionCreators.cleanCreatingProposal(); this.context.router.goBack(); } handleTitleChange(event) { this.setState({title : event}); CreatingProposalStore.proposal.fields.title = event; } handleDescriptionChange(event) { this.setState({description : event}); CreatingProposalStore.proposal.fields.description = event; } handleSelectInlineClick(event) { this.setState({event: event[0]}); CreatingProposalStore.proposal.type = event[0]; } handleStepsBarClick() { const {params} = this.props; ProposalActionCreators.mergeCreatingProposal(CreatingProposalStore.proposal); if (params.proposalId) { this.context.router.push('/proposal-type-edit/' + params.proposalId); } else { this.context.router.push('/proposal-type-edit/'); } } getProposalColor() { let color; if (CreatingProposalStore.proposal.selectedType) { switch (CreatingProposalStore.proposal.selectedType) { case 'leisure': color = 'pink'; break; case 'experience': color = 'green'; break; default: color = 'blue'; break; } } else { switch (CreatingProposalStore.proposal.type) { case 'sports': case 'hobbies': case 'games': color = 'pink'; break; case 'shows': case 'restaurants': case 'plans': color = 'green'; break; default: color = 'blue'; break; } } return color; } renderSelectInline() { const {strings} = this.props; let component; const leisureOptions = [ { id: "sports", text: strings.sports }, { id: "hobbies", text: strings.hobbies }, { id: "games", text: strings.games } ]; const experienceOptions = [ { id: "shows", text: strings.shows }, { id: "restaurants", text: strings.restaurants }, { id: "plans", text: strings.plans } ]; if (CreatingProposalStore.proposal.selectedType) { switch (CreatingProposalStore.proposal.selectedType) { case 'leisure': component = <SelectInline color={'pink'} options={leisureOptions} defaultOption={CreatingProposalStore.proposal.type} onClickHandler={this.handleSelectInlineClick}/>; break; case 'experience': component = <SelectInline color={'green'} options={experienceOptions} defaultOption={CreatingProposalStore.proposal.type} onClickHandler={this.handleSelectInlineClick}/>; break; default: component = null; break; } } else { switch (CreatingProposalStore.proposal.type) { case 'sports': case 'hobbies': case 'games': component = <SelectInline color={'pink'} options={leisureOptions} defaultOption={CreatingProposalStore.proposal.type} onClickHandler={this.handleSelectInlineClick}/>; break; case 'shows': case 'restaurants': case 'plans': component = <SelectInline color={'green'} options={experienceOptions} defaultOption={CreatingProposalStore.proposal.type} onClickHandler={this.handleSelectInlineClick}/>; break; default: component = null; break; } } return component; } render() { const {strings} = this.props; const canContinue = CreatingProposalStore.proposal.fields.title !== "" && CreatingProposalStore.proposal.fields.description !== "" && CreatingProposalStore.proposal.type !== ""; return ( CreatingProposalStore.proposal ? <div className='views'> <div className="view view-main proposal-basic-edit"> <TopNavBar background={'transparent'} iconLeft={'arrow-left'} firstIconRight={'x'} textCenter={CreatingProposalStore.proposal.id ? strings.editProposal : strings.publishProposal} textSize={'small'} onLeftLinkClickHandler={this.topNavBarLeftLinkClick} onRightLinkClickHandler={this.topNavBarRightLinkClick}/> <div className="proposal-wrapper"> <h2>{strings.title}</h2> <div> {this.renderSelectInline()} <div className={'image-wrapper'}> <img src={'../../../../img/default-upload-image.png'}/> </div> <Input size={'small'} placeholder={strings.titlePlaceholder} defaultValue={CreatingProposalStore.proposal.fields.title} onChange={this.handleTitleChange}/> <Textarea defaultValue={CreatingProposalStore.proposal.fields.description} placeholder={strings.descriptionPlaceholder} onChange={this.handleDescriptionChange}/> </div> </div> </div> <StepsBar color={this.getProposalColor()} totalSteps={5} currentStep={0} continueText={strings.stepsBarContinueText} cantContinueText={strings.stepsBarCantContinueText} canContinue={canContinue} onClickHandler={this.handleStepsBarClick}/> </div> : null ); } } ProposalBasicEditPage.defaultProps = { strings: { publishProposal : 'Publish proposal', editProposal : 'Edit proposal', title : 'What is your proposal?', titlePlaceholder : 'Propose title', descriptionPlaceholder : 'Explain how you want to carry it out...', shows : 'Events', restaurants : 'Gourmet', plans : 'Plans', sports : 'Sports', hobbies : 'Hobbys', games : 'Games', stepsBarCantContinueText : 'You cannot continue', stepsBarContinueText : 'Continue', } };
frontend/src/Settings/ImportLists/ImportListExclusions/EditImportListExclusionModalContent.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import Form from 'Components/Form/Form'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import Button from 'Components/Link/Button'; import SpinnerErrorButton from 'Components/Link/SpinnerErrorButton'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { inputTypes, kinds } from 'Helpers/Props'; import { stringSettingShape } from 'Helpers/Props/Shapes/settingShape'; import styles from './EditImportListExclusionModalContent.css'; function EditImportListExclusionModalContent(props) { const { id, isFetching, error, isSaving, saveError, item, onInputChange, onSavePress, onModalClose, onDeleteImportListExclusionPress, ...otherProps } = props; const { artistName, foreignId } = item; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> {id ? 'Edit Import List Exclusion' : 'Add Import List Exclusion'} </ModalHeader> <ModalBody className={styles.body}> { isFetching && <LoadingIndicator /> } { !isFetching && !!error && <div>Unable to add a new import list exclusion, please try again.</div> } { !isFetching && !error && <Form {...otherProps} > <FormGroup> <FormLabel>Entity Name</FormLabel> <FormInputGroup type={inputTypes.TEXT} name="artistName" helpText="The name of the artist/album to exclude (can be anything meaningful)" {...artistName} onChange={onInputChange} /> </FormGroup> <FormGroup> <FormLabel>Musicbrainz Id</FormLabel> <FormInputGroup type={inputTypes.TEXT} name="foreignId" helpText="The Musicbrainz Id of the artist/album to exclude" {...foreignId} onChange={onInputChange} /> </FormGroup> </Form> } </ModalBody> <ModalFooter> { id && <Button className={styles.deleteButton} kind={kinds.DANGER} onPress={onDeleteImportListExclusionPress} > Delete </Button> } <Button onPress={onModalClose} > Cancel </Button> <SpinnerErrorButton isSpinning={isSaving} error={saveError} onPress={onSavePress} > Save </SpinnerErrorButton> </ModalFooter> </ModalContent> ); } const ImportListExclusionShape = { artistName: PropTypes.shape(stringSettingShape).isRequired, foreignId: PropTypes.shape(stringSettingShape).isRequired }; EditImportListExclusionModalContent.propTypes = { id: PropTypes.number, isFetching: PropTypes.bool.isRequired, error: PropTypes.object, isSaving: PropTypes.bool.isRequired, saveError: PropTypes.object, item: PropTypes.shape(ImportListExclusionShape).isRequired, onInputChange: PropTypes.func.isRequired, onSavePress: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired, onDeleteImportListExclusionPress: PropTypes.func }; export default EditImportListExclusionModalContent;
src/index.js
rangle/redux-gtm
const createMiddleware = require('./create-middleware'); const createMetaReducer = require('./create-meta-reducer'); // Extensions const logger = require('./extensions/logger'); const offlineWeb = require('./extensions/offline-web'); const offlineReactNative = require('./extensions/offline-react-native'); // Event Helpers const createGAevent = require('./event-helpers/create-ga-event'); const createGApageview = require('./event-helpers/create-ga-pageview'); const createGAuserTiming = require('./event-helpers/create-ga-user-timing'); module.exports = { createMiddleware, createMetaReducer, Extensions: { logger, offlineWeb, offlineReactNative, }, EventHelpers: { createGAevent, createGApageview, createGAuserTiming, }, };
example/app.js
raodurgesh/react-virtualized-chatbox
import React, { Component } from 'react'; import InputBox from './input-box'; import ChatBox from '../dist/index' export default class App extends Component { constructor(props) { super(props); this.listComponent = {}; this.state = { list: [90, 91, 92,93] } this._rowRenderer = this._rowRenderer.bind(this); this._loadMoreRows = this._loadMoreRows.bind(this); this._getListComponent = this._getListComponent.bind(this); this._rowHeight = this._rowHeight.bind(this); this._onKeyBoardEnter = this._onKeyBoardEnter.bind(this); } componentWillUpdate(nextProps, nextState) { } render() { return ( <div> <ChatBox list={this.state.list} height={500} rowHeight={this._rowHeight} rowRenderer={this._rowRenderer} loadMoreRows={this._loadMoreRows} getListComponent={this._getListComponent} /> <InputBox onEnter={this._onKeyBoardEnter} /> </div> ) } _rowHeight({ index }) { switch (index % 3) { case 1: return 40; case 2: return 60; default: return 100; } } _getListComponent(ref) { this.listComponent = ref; } _loadMoreRows(params) { setTimeout(() => { let list = [...this.state.list]; for (let i = 0; i < 100; i++) list = params.append ? [...list, list[list.length - 1] + 1] : [list[0] - 1, ...list]; this.setState({ list }) }, 2000) } _rowRenderer({ key, index, style, isVisible, overFlow, isScrolling }) { if (isVisible) { let row = (overFlow && index == 0) ? <div style ={{'textAlign': 'center'}} >Loading...</div> : '' let _style = index %2 ==0 ? {'backgroundColor': '#eee','paddingLeft':'5px'} :{'backgroundColor': '#ddd','paddingLeft':'5px'}; return ( <div key={key} style={{...style,..._style }} > {row} {this.state.list[index]} </div> ) } } _onKeyBoardEnter(val){ let list = [...this.state.list]; list = [...list, val] this.setState({ list }) } }
ChannelListings/Content/Scripts/jquery-1.9.1.min.js
ericrrichards/tvlistings
/*! 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);
ajax/libs/forerunnerdb/1.3.14/fdb-core+views.min.js
sashberd/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/View")}b.exports=d},{"../lib/Core":5,"../lib/View":24}],2:[function(a,b,c){var d=a("./Shared"),e=(a("./Path"),function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})});d.addModule("ActiveBucket",e),d.synthesize(e.prototype,"primaryKey"),d.mixin(e.prototype,"Mixin.Sorting"),e.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},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.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},e.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},e.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},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Path":21,"./Shared":23}],3:[function(a,b,c){var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a){this.init.apply(this,arguments)};l.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._groups=[],this._metrics=new f,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._subsetOf(this)},d.addModule("Collection",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.CRUD"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Sorting"),d.mixin(l.prototype,"Mixin.Matching"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Core,l.prototype.crc=k,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.data=function(){return this._data},l.prototype.drop=function(){if("dropped"===this._state)return!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._groups&&this._groups.length){var a,b=[];for(a=0;a<this._groups.length;a++)b.push(this._groups[a]);for(a=0;a<b.length;a++)this._groups[a].removeCollection(this)}return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._groups,delete this._metrics,!0}return!1},l.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},l.prototype._onInsert=function(a,b){this.emit("insert",a,b)},l.prototype._onUpdate=function(a){this.emit("update",a)},l.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(l.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),l.prototype.setData=function(a,b,c){if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},l.prototype.rebuildPrimaryKeyIndex=function(a){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'ForerunnerDB.Collection "'+this.name()+'": 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=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},l.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},l.prototype.truncate=function(){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.deferEmit("change",{type:"truncate"}),this},l.prototype.upsert=function(a,b){if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),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);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},l.prototype.update=function(a,b,c){b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},l.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'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},l.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},l.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=(this.decouple(a),!1),r=!1;for(o in b)if(b.hasOwnProperty(o)){if(g=!1,"$"===o.substr(0,1))switch(o){case"$key":case"$index":g=!0;break;default:g=!0,r=this.updateObject(a,b[o],c,d,e,o),q=q||r}if(this._isPositionalKey(o)&&(g=!0,o=o.substr(0,o.length-2),l=new h(e+"."+o),a[o]&&a[o]instanceof Array&&a[o].length)){for(i=[],j=0;j<a[o].length;j++)this._match(a[o][j],l.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[o][i[j]],b[o+".$"],c,d,e+"."+o,f),q=q||r}if(!g)if(f||"object"!=typeof b[o])switch(f){case"$inc":this._updateIncrement(a,o,b[o]),q=!0;break;case"$push":if(void 0===a[o]&&this._updateProperty(a,o,[]),!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+o+")";if(void 0!==b[o].$position&&b[o].$each instanceof Array)for(A=b[o].$position,k=b[o].$each.length,j=0;k>j;j++)this._updateSplicePush(a[o],A+j,b[o].$each[j]);else if(b[o].$each instanceof Array)for(k=b[o].$each.length,j=0;k>j;j++)this._updatePush(a[o],b[o].$each[j]);else this._updatePush(a[o],b[o]);q=!0;break;case"$pull":if(a[o]instanceof Array){for(i=[],j=0;j<a[o].length;j++)this._match(a[o][j],b[o],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[o],i[k]),q=!0}break;case"$pullAll":if(a[o]instanceof Array){if(!(b[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+o+")";if(i=a[o],k=i.length,k>0)for(;k--;){for(A=0;A<b[o].length;A++)i[k]===b[o][A]&&(this._updatePull(a[o],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[o]&&this._updateProperty(a,o,[]),!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[o],x=w.length,y=!0,z=d&&d.$addToSet;for(b[o].$key?(u=!1,v=new h(b[o].$key),t=v.value(b[o])[0],delete b[o].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[o])[0]):(t=JSON.stringify(b[o]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[o],b[o]),q=!0);break;case"$splicePush":if(void 0===a[o]&&this._updateProperty(a,o,[]),!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+o+")";var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,A>a[o].length&&(A=a[o].length),this._updateSplicePush(a[o],A,b[o]),q=!0;break;case"$move":if(!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+o+")";for(j=0;j<a[o].length;j++)if(this._match(a[o][j],b[o],"",{})){var B=b.$index;if(void 0===B)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[o],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,o,b[o]),q=!0;break;case"$rename":this._updateRename(a,o,b[o]),q=!0;break;case"$unset":this._updateUnset(a,o),q=!0;break;case"$pop":if(!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+o+")";this._updatePop(a[o],b[o])&&(q=!0);break;default:a[o]!==b[o]&&(this._updateProperty(a,o,b[o]),q=!0)}else if(null!==a[o]&&"object"==typeof a[o])if(m=a[o]instanceof Array,n=b[o]instanceof Array,m||n)if(!n&&m)for(j=0;j<a[o].length;j++)r=this.updateObject(a[o][j],b[o],c,d,e+"."+o,f),q=q||r;else a[o]!==b[o]&&(this._updateProperty(a,o,b[o]),q=!0);else r=this.updateObject(a[o],b[o],c,d,e+"."+o,f),q=q||r;else a[o]!==b[o]&&(this._updateProperty(a,o,b[o]),q=!0)}return q},l.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},l.prototype._updateProperty=function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Collection: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"')},l.prototype._updateIncrement=function(a,b,c){a[b]+=c},l.prototype._updateSpliceMove=function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')},l.prototype._updateSplicePush=function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},l.prototype._updatePush=function(a,b){a.push(b)},l.prototype._updatePull=function(a,b){a.splice(b,1)},l.prototype._updateMultiply=function(a,b,c){a[b]*=c},l.prototype._updateRename=function(a,b,c){a[c]=a[b],delete a[b]},l.prototype._updateUnset=function(a,b){delete a[b]},l.prototype._updatePop=function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c},l.prototype.remove=function(a,b,c){var d,e,f,g,h,i,j,k,l=this;if(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),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};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);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return d},l.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},l.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},100))},l.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[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},l.prototype.insert=function(a,b,c){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)},l.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=(this._deferTime.insert,[]),i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},l.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;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)},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!1;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"},l.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},l.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},l.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},l.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},l.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},l.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},l.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},l.prototype.subset=function(a,b){var c=this.find(a,b);return(new l)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},l.prototype.subsetOf=function(){return this.__subsetOf},l.prototype._subsetOf=function(a){return this.__subsetOf=a,this},l.prototype.distinct=function(a,b,c){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},l.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},l.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new l,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},l.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},l.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},l.prototype.find=function(a,b){a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=this._metrics.create("find"),x=this,y=!0,z={},A=[],B={},C=function(b){return x._match(b,a,"and",B)};if(w.start(),a){if(w.time("analyseQuery"),c=this._analyseQuery(a,b,w),w.time("analyseQuery"),w.data("analysis",c),c.hasJoin&&c.queriesJoin){for(w.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],z[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);w.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(w.data("index.potential",c.indexMatch),w.data("index.used",c.indexMatch[0].index),w.time("indexLookup"),e=c.indexMatch[0].lookup,w.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(y=!1)):w.flag("usedIndex",!1),y&&(e&&e.length?(d=e.length,w.time("tableScan: "+d),e=e.filter(C)):(d=this._data.length,w.time("tableScan: "+d),e=this._data.filter(C)),b.$orderBy&&(w.time("sort"),e=this.sort(b.$orderBy,e),w.time("sort")),w.time("tableScan: "+d)),b.limit&&e&&e.length>b.limit&&(e.length=b.limit,w.data("limit",b.limit)),b.$decouple&&(w.time("decouple"),e=this.decouple(e),w.time("decouple"),w.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n];break;default:"$$."===n.substr(0,3)}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:A.push(e[t])}w.data("flag.join",!0)}if(A.length){for(w.time("removalQueue"),v=0;v<A.length;v++)u=e.indexOf(A[v]),u>-1&&e.splice(u,1);w.time("removalQueue")}if(b.transform){for(w.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.transform(e[v]));w.time("transform"),w.data("flag.transform",!0)}return this._transformEnabled&&this._transformOut&&(w.time("transformOut"),e=this.transformOut(e),w.time("transformOut")),w.data("results",e.length),w.stop(),e.__fdbOp=w,e}return w.stop(),e=[],e.__fdbOp=w,e},l.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},l.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}},l.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},l.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},l.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},l.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},l.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'ForerunnerDB.Collection "'+this.name()+'": $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)},l.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},l.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.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(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},l.prototype._queryReferencesCollection=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._queryReferencesCollection(a[d],b,c)}return!1},l.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},l.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},l.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},l.prototype.ensureIndex=function(a,b){this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default: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"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},l.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},l.prototype.lastOp=function(){return this._metrics.list()},l.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection 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},e.prototype.collection=function(a,b){if(a)return this._collection[a]||this.debug()&&console.log("Creating collection "+a),this._collection[a]=this._collection[a]||new l(a).db(this),void 0!==b&&this._collection[a].primaryKey(b),this._collection[a];throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection with undefined name!'},e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c},d.finishModule("Collection"),b.exports=l},{"./Crc":6,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Path":21,"./Shared":23}],4:[function(a,b,c){var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){this._name=a,this._data=new g("__FDB__cg_data_"+this._name),this._collections=[],this._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"),g=a("./Collection"),e=d.modules.Core,f=d.modules.Core.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"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups.push(this),a.chain(this),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),b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1)),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);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(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),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":3,"./Shared":23}],5:[function(a,b,c){var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},i.prototype.moduleLoaded=h({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()}},"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.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Collection.js"),f=a("./Metrics.js"),g=a("./Crc.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.crc=g,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new e).setData(a)},i.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},i.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},i.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},i.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=d.concat("string"===e?c.peek(a):c.find(a)));return d},i.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},i.prototype.drop=function(a){if("dropped"!==this._state){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)}return!0},b.exports=i},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":10,"./Overload":20,"./Shared":23}],6:[function(a,b,c){var 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}();b.exports=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}},{}],7:[function(a,b,c){var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),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("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=new(f.create(2,this.sortAsc)),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,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},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){return this._data[this._itemHash(a,this._keys)]||[]},g.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}},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.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":21,"./Shared":23}],8:[function(a,b,c){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._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.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.finishModule("IndexHashMap"),b.exports=f},{"./Path":21,"./Shared":23}],9:[function(a,b,c){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,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return 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":23}],10:[function(a,b,c){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":19,"./Shared":23}],11:[function(a,b,c){var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){var d,e=0,f=a("./Overload");d={decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},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},debug: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}])},b.exports=d},{"./Overload":20}],14:[function(a,b,c){var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){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}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]: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){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(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||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":20}],16:[function(a,b,c){var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)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],f,d));h++);if(g){if("or"===c)return!0}else n=!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],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)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],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){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"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.distinctLookup=d.distinctLookup||{};for(var m in c)if(c.hasOwnProperty(m))return d.distinctLookup[m]=d.distinctLookup[m]||{},d.distinctLookup[m][b[m]]?!1:(d.distinctLookup[m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],17:[function(a,b,c){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},{}],18:[function(a,b,c){var d={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(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}),!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},willTrigger:function(a,b){return this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++){if(i=f[g],this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),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=d},{}],19:[function(a,b,c){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":21,"./Shared":23}],20:[function(a,b,c){var d=function(a){if(a){var b,c,d,f,g,h;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(f=b.replace(/ /g,""),-1===f.indexOf("*"))d[f]=a[b];else for(h=e(f),g=0;g<h.length;g++)d[h[g]]||(d[h[g]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return a[b].apply(this,arguments)}else{for(b=0;b<arguments.length;b++)e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),f.push(e);if(d=f.join(","),a[d])return a[d].apply(this,arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return a[d+",..."].apply(this,arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}},e=function(a){var b,c,d=[],f=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<f.length;c++)b=a.replace("*",f[c]),d=d.concat(e(b));else d.push(a);return d};b.exports=d},{}],21:[function(a,b,c){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.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 f.push(b?{path:g,value:a[d]}:{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]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},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.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.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":23}],22:[function(a,b,c){var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires an in, out and process argument to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)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"dropped"!==this._state&&(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)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":23}],23:[function(a,b,c){var d={version:"1.3.14",modules:{},_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.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},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:a("./Overload"),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")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Overload":20}],24:[function(a,b,c){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._name=a,this._groups=[],this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f("__FDB__view_privateData_"+this._name)},d.addModule("View",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"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Core,i=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.find=function(a,b){return this.publicData().find(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket()}return this},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(a.type){case"setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(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++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._groups,delete this._listeners,delete this._querySettings,delete this._db,!0):!1},l.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db},l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){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)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(), this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.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),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a=this.publicData();this._privateData.remove(),a.remove(),this._privateData.insert(this._from.find(this._querySettings.query,this._querySettings.options)),a._linked}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0},l.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._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},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'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;var d=new l(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){return this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.View: Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a]},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b=[];for(a in this._view)this._view.hasOwnProperty(a)&&b.push({name:a,count:this._view[a].count()});return b},d.finishModule("View"),b.exports=l},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":22,"./Shared":23}]},{},[1]);
packages/material-ui-icons/src/KeyboardBackspaceOutlined.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 11H6.83l3.58-3.59L9 6l-6 6 6 6 1.41-1.41L6.83 13H21v-2z" /> , 'KeyboardBackspaceOutlined');
test/actions/index.spec.js
noahpeden/adoptfund
import React from 'react'; import { mount, shallow } from 'enzyme'; import { expect, assert } from 'chai'; import sinon from 'sinon' import * as actions from '../../public/lib/actions/index' describe('actions', () => { it('should create an action to make an array of featured families', () => { const featured = { somejson: 'somejson', somemorejson: 'somemorejson' } const expectedAction = { type: 'FEATURED', featured: { somejson: 'somejson', somemorejson: 'somemorejson' }, } expect(actions.featured(featured)).to.deep.equal(expectedAction) }) it('should create an action for a user to sign in', () => { const email = 'jim@aol.com' const password = 'password' const user = 'jim' const expectedAction = { data: 'j', type: 'SIGN_IN', } expect(actions.signIn(email, password, user)).to.deep.equal(expectedAction) }) it('should create an action for a user to sign out', () => { const email = 'jim@aol.com' const password = 'password' const user = 'jim' const expectedAction = { data: 'jim@aol.com', type: 'SIGN_OUT', } expect(actions.signOut(email, password, user)).to.deep.equal(expectedAction) }) it('should create an action for a user to search a family', () => { const searchedFamily = { somejson: 'somejson', somemorejson: 'somemorejson' } const expectedAction = { type: 'SEARCHED', searchedFamily: { somejson: 'somejson', somemorejson: 'somemorejson' }, } expect(actions.searched(searchedFamily)).to.deep.equal(expectedAction) }) it('should store selected family', () => { const info = { somejson: 'somejson', somemorejson: 'somemorejson' } const expectedAction = { type: 'SELECTED', info: { somejson: 'somejson', somemorejson: 'somemorejson' }, } expect(actions.storeSelected(info)).to.deep.equal(expectedAction) }) it('should save a donation for a family', () => { const familyId = { somejson: 'somejson', somemorejson: 'somemorejson' } const expectedAction = { type: 'DONATION-FAMILY', familyId: { somejson: 'somejson', somemorejson: 'somemorejson' }, } expect(actions.saveFamily(familyId)).to.deep.equal(expectedAction) }) it('should store donations for selected family', () => { const donations = { somejson: 'somejson', somemorejson: 'somemorejson' } const expectedAction = { type: 'FAMILY-DONATIONS', donations: { somejson: 'somejson', somemorejson: 'somemorejson' }, } expect(actions.familyDonations(donations)).to.deep.equal(expectedAction) }) })
ajax/libs/6to5/1.13.9/browser.js
cdnjs/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(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(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.9.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,new Position]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=7){isKeyword=isEcma7Keyword}else if(options.ecmaVersion===6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc;this.startLoc=tokStartLoc;this.endLoc=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(forceRegexp){lastEnd=tokEnd;readToken(forceRegexp);return new Token}getToken.jumpTo=function(pos,reAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokRegexpAllowed=reAllowed;skipSpace()};getToken.noRegexp=function(){tokRegexpAllowed=false};getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokRegexpAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inXJSChildExpression;var metParenL;var inTemplate;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=new Position;inFunction=inGenerator=inAsync=strict=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _async={keyword:"async"},_await={keyword:"await",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield,await:_await,async:_async};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_bquote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _ltSlash={type:"</"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _doubleColon={type:"::",beforeExpr:true};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:10,beforeExpr:true};var _lt={binop:7,beforeExpr:true},_gt={binop:7,beforeExpr:true};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,arrow:_arrow,bquote:_bquote,dollarBraceL:_dollarBraceL,star:_star,assign:_assign,xjsName:_xjsName,xjsText:_xjsText,doubleColon:_doubleColon,exponent:_exponent};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];function makePredicate(words){words=words.split(" ");var f="",cats=[];out:for(var i=0;i<words.length;++i){for(var j=0;j<cats.length;++j)if(cats[j][0].length==words[i].length){cats[j].push(words[i]);continue out}cats.push([words[i]])}function compareTo(arr){if(arr.length==1)return f+="return str === "+JSON.stringify(arr[0])+";";f+="switch(str){";for(var i=0;i<arr.length;++i)f+="case "+JSON.stringify(arr[i])+":";f+="return true}return false;"}if(cats.length>3){cats.sort(function(a,b){return b.length-a.length});f+="switch(str.length){";for(var i=0;i<cats.length;++i){var cat=cats[i];f+="case "+cat[0].length+":";compareTo(cat)}f+="}"}else{compareTo(words)}return new Function("str",f)}var isReservedWord3=makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");var isReservedWord5=makePredicate("class enum extends super const export import");var isStrictReservedWord=makePredicate("implements interface let package private protected public static yield");var isStrictBadIdWord=makePredicate("eval arguments");var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=makePredicate(ecma5AndLessKeywords);var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=makePredicate(ecma6AndLessKeywords);var isEcma7Keyword=makePredicate(ecma6AndLessKeywords+" async await");var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var newline=/[\n\r\u2028\u2029]/;var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(){this.line=tokCurLine;this.column=tokPos-tokLineStart}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokRegexpAllowed=true;metParenL=0;inTemplate=inXJSChild=inXJSTag=false}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=new Position;tokType=type;if(shouldSkipSpace!==false&&!(inXJSChild&&tokType!==_braceL)){skipSpace()}tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&new Position;var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&new Position)}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&new Position;var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&new Position)}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokRegexpAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code)return finishOp(code===124?_logicalOR:_logicalAND,2);if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(next===61){size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}if(next===47){size=2;return finishOp(_ltSlash,size)}return code===60?finishOp(_lt,size):finishOp(_gt,size,!inXJSTag)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}if(code===125){++tokPos;return finishToken(_braceR,undefined,false)}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR,undefined,!inXJSChildExpression);case 63:++tokPos;return finishToken(_question);case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_doubleColon)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_bquote,undefined,false)}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(forceRegexp){if(!forceRegexp)tokStart=tokPos;else tokPos=tokStart+1;if(options.locations)tokStartLoc=new Position;if(forceRegexp)return readRegexp();if(tokPos>=inputLen)return finishToken(_eof);var code=input.charCodeAt(tokPos);if(inXJSChild&&tokType!==_braceL&&code!==60&&code!==123&&code!==125){return readXJSText(["<","{"])}if(inTemplate)return getTemplateToken(code);if(isIdentifierStart(code)||code===92)return readWord();var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){++tokPos;var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote){++tokPos;return finishToken(_string,out)}if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){raise(tokStart,"Unterminated string constant")}out+=String.fromCharCode(ch)}}}function readTmplString(){var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123)return finishToken(_string,out);if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");tokPos++;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){break}str+=ch}if(str[0]==="#"&&str[1]==="x"){entity=String.fromCharCode(parseInt(str.substr(2),16))}else if(str[0]==="#"){entity=String.fromCharCode(parseInt(str.substr(1),10))}else{entity=XHTMLEntities[str]}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word,first=true,start=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)||inXJSTag&&ch===45){if(containsEsc)word+=nextChar();++tokPos}else if(ch===92&&!inXJSTag){if(!containsEsc)word=input.slice(start,tokPos);containsEsc=true;if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr}else{break}first=false}return containsEsc?word:input.slice(start,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function next(){lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,allowSpread,checkType){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.type==="Property"&&prop.kind!=="init")unexpected(prop.key.start);toAssignable(prop.value,false,checkType)}break;case"ArrayExpression":node.type="ArrayPattern";for(var i=0,lastI=node.elements.length-1;i<=lastI;i++){toAssignable(node.elements[i],i===lastI,checkType)}break;case"SpreadElement":if(allowSpread){toAssignable(node.argument,false,checkType);checkSpreadAssign(node.argument)}else{unexpected(node.start)}break;default:if(checkType)unexpected(node.start)}}return node}function checkSpreadAssign(node){if(node.type!=="Identifier"&&node.type!=="ArrayPattern")unexpected(node.start)}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return; var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,isBinding?"Binding "+expr.name+" in strict mode":"Assigning to "+expr.name+" in strict mode");break;case"MemberExpression":if(!isBinding)break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"SpreadProperty":case"SpreadElement":case"VirtualPropertyExpression":break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement();node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(){if(tokType===_slash||tokType===_assign&&tokVal=="/=")readToken(true);var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _async:return parseAsync(node,true);case _function:return parseFunctionStatement(node);case _class:return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _var:case _let:case _const:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:return parseExport(node);case _import:return parseImport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name&&expr.type==="Identifier"&&eat(_colon))return parseLabeledStatement(node,maybeName,expr);else return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement();labels.pop();expect(_while);node.test=parseParenExpression();semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of")&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var init=parseExpression(false,true);if(tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of"){checkLVal(init);return parseForIn(node,init)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseAsync(node,isStatement){if(options.ecmaVersion<7){unexpected()}next();switch(tokType){case _function:next();return parseFunction(node,isStatement,true);if(!isStatement)unexpected();case _name:var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(node,[id],true)}case _parenL:var oldParenL=++metParenL;var exprList=[];next();if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}default:unexpected()}}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement();node.alternate=eat(_else)?parseStatement():null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement())}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseIdent();if(strict&&isStrictBadIdWord(clause.param.name))raise(clause.param.start,"Binding "+clause.param.name+" in strict mode");expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement();labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement();return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement();labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement();node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=options.ecmaVersion>=6?toAssignable(parseExprAtom()):parseIdent();checkLVal(decl.id,true);decl.init=eat(_eq)?parseExpression(true,noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noComma,noIn){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn);if(!noComma&&tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn){var start=storeCurrentPos();var left=parseMaybeConditional(noIn);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}return left}function parseMaybeConditional(noIn){var start=storeCurrentPos();var expr=parseExprOps(noIn);if(eat(_question)){var node=startNodeAt(start);node.test=expr;node.consequent=parseExpression(true);expect(_colon);node.alternate=parseExpression(true,noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate,nodeType;if(tokType===_ellipsis){nodeType="SpreadElement"}else{nodeType=update?"UpdateExpression":"UnaryExpression";node.operator=tokVal;node.prefix=true}tokRegexpAllowed=true;next();node.argument=parseMaybeUnary();if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,nodeType)}var start=storeCurrentPos();var expr=parseExprSubscripts();while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(){var start=storeCurrentPos();return parseSubscripts(parseExprAtom(),start)}function parseSubscripts(base,start,noCalls){if(eat(_doubleColon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_bquote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _await:if(inAsync)return parseAwait();case _name:var start=storeCurrentPos();var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _xjsText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:var start=storeCurrentPos();var val,exprList;next();if(options.ecmaVersion>=7&&tokType===_for){val=parseComprehension(startNodeAt(start),true)}else{var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){val=parseArrowExpression(startNodeAt(start),exprList)}else{if(!val)unexpected(lastStart);if(options.ecmaVersion>=6){for(var i=0;i<exprList.length;i++){if(exprList[i].type==="SpreadElement")unexpected()}}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;val=finishNode(par,"ParenthesizedExpression")}}}return val;case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true);return finishNode(node,"ArrayExpression");case _braceL:return parseObj();case _async:return parseAsync(startNode(),false);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _bquote:return parseTemplate();case _lt:return parseXJSElement();default:unexpected()}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplate(){var node=startNode();node.expressions=[];node.quasis=[];inTemplate=true;next();for(;;){var elem=startNode();elem.value={cooked:tokVal,raw:input.slice(tokStart,tokEnd)};elem.tail=false;next();node.quasis.push(finishNode(elem,"TemplateElement"));if(tokType===_bquote){elem.tail=true;break}inTemplate=false;expect(_dollarBraceL);node.expressions.push(parseExpression());inTemplate=true;tokPos=tokEnd;expect(_braceR)}inTemplate=false;next();return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];var origInXJSChildExpression=inXJSChildExpression;inXJSChildExpression=false;next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator,isAsync;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_ellipsis){if(isAsync||isGenerator)unexpected();prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}parsePropertyName(prop);if(eat(_colon)){prop.value=parseExpression(true);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")){if(isGenerator||isAsync)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";prop.value=prop.key;prop.shorthand=true}else unexpected();checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}inXJSChildExpression=origInXJSChildExpression;return finishNode(node,"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;node.params=[];if(options.ecmaVersion>=6){node.defaults=[];node.rest=null;node.generator=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){if(isAsync&&tokType===_star)unexpected();node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);var defaults=node.defaults,hasDefaults=false;for(var i=0,lastI=params.length-1;i<=lastI;i++){var param=params[i];if(param.type==="AssignmentExpression"&&param.operator==="="){hasDefaults=true;params[i]=param.left;defaults.push(param.right)}else{toAssignable(param,i===lastI,true);defaults.push(null);if(param.type==="SpreadElement"){params.length--;node.rest=param.argument;break}}}node.params=params;if(!hasDefaults)node.defaults=[];parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionParams(node){var defaults=[],hasDefaults=false;expect(_parenL);for(;;){if(eat(_parenR)){break}else if(options.ecmaVersion>=6&&eat(_ellipsis)){node.rest=toAssignable(parseExprAtom(),false,true);checkSpreadAssign(node.rest);expect(_parenR);defaults.push(null);break}else{node.params.push(options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent());if(options.ecmaVersion>=6){if(eat(_eq)){hasDefaults=true;defaults.push(parseExpression(true))}else{defaults.push(null)}}if(!eat(_comma)){expect(_parenR);break}}}if(hasDefaults)node.defaults=defaults}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseExpression(true);node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash);if(node.rest)checkFunctionParam(node.rest,nameHash)}}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;node.superClass=eat(_extends)?parseExpression():null;var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}var isGenerator=eat(_star);parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}method.value=parseMethod(isGenerator,isAsync);classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseExprList(close,allowTrailingComma,allowEmpty){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma)elts.push(null);else elts.push(parseExpression(true))}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||tokType===_async){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){node.declaration=parseExpression(true);node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(tokType===_name&&tokVal==="from"){next();node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent(true)}else{node.name=null}nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom();node.kind=""}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected();node.kind=node.specifiers[0]["default"]?"default":"named"}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();if(tokType!==_name||tokVal!=="as")unexpected();next();node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent()}else{node.name=null}checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseExpression(true)}return finishNode(node,"YieldExpression")}function parseAwait(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseExpression(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=toAssignable(parseExprAtom());checkLVal(block.left,true);if(tokType!==_name||tokVal!=="of")unexpected();next();block.of=true;block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedXJSName(object){if(object.type==="XJSIdentifier"){return object.name}if(object.type==="XJSNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="XJSMemberExpression"){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function parseXJSIdentifier(){var node=startNode();if(tokType===_xjsName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"XJSIdentifier")}function parseXJSNamespacedName(){var node=startNode();node.namespace=parseXJSIdentifier();expect(_colon);node.name=parseXJSIdentifier();return finishNode(node,"XJSNamespacedName")}function parseXJSMemberExpression(){var start=storeCurrentPos();var node=parseXJSIdentifier();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseXJSIdentifier();node=finishNode(newNode,"XJSMemberExpression")}return node}function parseXJSElementName(){switch(nextChar()){case":":return parseXJSNamespacedName();case".":return parseXJSMemberExpression();default:return parseXJSIdentifier()}}function parseXJSAttributeName(){if(nextChar()===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){switch(tokType){case _braceL:var node=parseXJSExpressionContainer();if(node.expression.type==="XJSEmptyExpression"){raise(node.start,"XJS attributes must only be assigned a non-empty "+"expression")}return node;case _lt:return parseXJSElement();case _xjsText:return parseExprAtom();default:raise(tokStart,"XJS value should be either an expression or a quoted XJS text")}}function parseXJSEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"XJSEmptyExpression")}function parseXJSExpressionContainer(){var node=startNode();var origInXJSTag=inXJSTag,origInXJSChild=inXJSChild;inXJSTag=false;inXJSChild=false;inXJSChildExpression=origInXJSChild;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;inXJSChildExpression=false;expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag,origInXJSChildExpression=inXJSChildExpression;inXJSTag=inXJSChildExpression=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();inXJSChildExpression=origInXJSChildExpression;inXJSTag=origInXJSTag;expect(_braceR);node.type="XJSSpreadAttribute";node.start=tokStart1;node.end=lastEnd;if(options.locations){node.loc.start=tokStartLoc1;node.loc.end=lastEndLoc}if(options.ranges){node.range=[tokStart1,lastEnd]}return node}var node=startNode();node.name=parseXJSAttributeName();if(tokType===_eq){next();node.value=parseXJSAttributeValue()}else{node.value=null}return finishNode(node,"XJSAttribute")}function parseXJSChild(){switch(tokType){case _braceL:return parseXJSExpressionContainer();case _xjsText:return parseExprAtom();default:return parseXJSElement()}}function parseXJSOpeningElement(){var node=startNode(),attributes=node.attributes=[];var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;next();node.name=parseXJSElementName();while(tokType!==_eof&&tokType!==_slash&&tokType!==_gt){attributes.push(parseXJSAttribute())}inXJSTag=false;if(node.selfClosing=!!eat(_slash)){inXJSTag=origInXJSTag;inXJSChild=origInXJSChild}else{inXJSChild=true}expect(_gt);return finishNode(node,"XJSOpeningElement")}function parseXJSClosingElement(){var node=startNode();var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;tokRegexpAllowed=false;expect(_ltSlash);node.name=parseXJSElementName();skipSpace();inXJSChild=origInXJSChild;inXJSTag=origInXJSTag;tokRegexpAllowed=false;if(inXJSChild){tokPos=tokEnd}expect(_gt);return finishNode(node,"XJSClosingElement")}function parseXJSElement(){var node=startNode();var children=[];var origInXJSChild=inXJSChild;var openingElement=parseXJSOpeningElement();var closingElement=null;if(!openingElement.selfClosing){while(tokType!==_eof&&tokType!==_ltSlash){inXJSChild=true;children.push(parseXJSChild())}inXJSChild=origInXJSChild;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){raise(closingElement.start,"Expected corresponding XJS closing tag for '"+getQualifiedXJSName(openingElement.name)+"'")}}if(!origInXJSChild&&tokType===_lt){raise(tokStart,"Adjacent XJS elements must be wrapped in an enclosing tag")}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"XJSElement")}})},{}],2:[function(require,module,exports){(function(global){var transform=module.exports=require("./transformation/transform");transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i in _scripts){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transform":28}],3:[function(require,module,exports){module.exports=File; var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.opts=File.normaliseOptions(opts);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);this.uids={};this.ast={}}File.declarations=["extends","class-props","apply-constructor","tagged-template-literal","interop-require","to-array","arguments-to-array","object-spread"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,whitespace:true,blacklist:[],whitelist:[],sourceMap:false,comments:true,filename:"unknown",modules:"common",runtime:false,code:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.runtime===true){opts.runtime="to5Runtime"}transform._ensureTransformerNames("blacklist",opts.blacklist);transform._ensureTransformerNames("whitelist",opts.whitelist);return opts};File.prototype.toArray=function(node){if(t.isArrayExpression(node)){return node}var templateName="to-array";if(t.isIdentifier(node)&&node.name==="arguments"){templateName="arguments-to-array"}return t.callExpression(this.addDeclaration(templateName),[node])};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("unknown module formatter type "+type)}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.addDeclaration=function(name){if(!_.contains(File.declarations,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var ref;var runtimeNamespace=this.opts.runtime;if(runtimeNamespace){name=t.identifier(t.toIdentifier(name));return t.memberExpression(t.identifier(runtimeNamespace),name)}else{ref=util.template(name)}var uid=this.generateUidIdentifier(name);this.scope.push(name,uid,ref);return uid};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.parse=function(code){code=(code||"")+"";var self=this;this.code=code;code=this.parseShebang(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.ast=ast;this.scope=new Scope(ast.program);var self=this;_.each(transform.transformers,function(transformer){transformer.transform(self)})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;if(!opts.code){return{code:"",map:null,ast:ast}}var result=generate(ast,opts,this.code);if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}result.ast=result;return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name);scope=scope||this.scope;var uid;do{uid=this._generateUid(name)}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){return t.identifier(this.generateUid(name,scope))};File.prototype._generateUid=function(name){var uids=this.uids;var i=uids[name]||1;var id=name;if(i>1)id+=i;uids[name]=i+1;return"_"+id}},{"./generation/generator":5,"./transformation/transform":28,"./traverse/scope":68,"./types":71,"./util":73,lodash:104}],4:[function(require,module,exports){module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){if(this.format.semicolons)this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.slice(0,-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(!this.buf)return;if(this.format.compact)return;if(this.endsWith("{\n"))return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith(util.repeat(i,"\n")))return;var self=this;_.times(i,function(){self.newline(null,removeLast)});return}if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this.buf=this.buf.replace(/\n +$/,"\n");this._push("\n")};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){return this.buf.slice(-str.length)===str};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var chars=[].concat(cha);return _.contains(chars,_.last(buf))}},{"../util":73,lodash:104}],5:[function(require,module,exports){module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(opts){return _.merge({parentheses:true,semicolons:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent)}self.newline(lines)};if(this[node.type]){this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");var needsParens=parent!==node._parent&&n.needsParens(node,parent);if(needsParens)this.push("(");this[node.type](node,this.buildPrint(node),parent);if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node "+node.type+" "+JSON.stringify(node))}};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":71,"../util":73,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":16,"./position":19,"./source-map":20,"./whitespace":21,lodash:104}],6:[function(require,module,exports){exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(require,module,exports){exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],8:[function(require,module,exports){exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],9:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.ParenthesizedExpression=function(node,print){this.push("(");print(node.expression);this.push(")")};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");print.join(node.arguments,{separator:", "});this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" "+node.operator+" ");print(node.right)};exports.MemberExpression=function(node,print){print(node.object);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(node.object)&&util.isInteger(node.object.value)){this.push(".")}this.push(".");print(node.property)}}},{"../../types":71,"../../util":73}],10:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.XJSAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.XJSIdentifier=function(node){this.push(node.name)};exports.XJSNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.XJSMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.XJSSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.XJSExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.XJSElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.XJSOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.space();print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.XJSClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.XJSEmptyExpression=function(){}},{"../../types":71,lodash:104}],11:[function(require,module,exports){var t=require("../../types");exports._params=function(node,print){var self=this;this.push("(");print.join(node.params,{separator:", ",iterator:function(param,i){var def=node.defaults&&node.defaults[i];if(def){self.push(" = ");print(def)}}});if(node.rest){if(node.params.length){this.push(", ")}this.push("...");print(node.rest)}this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.space();print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.space();if(node.id)print(node.id);this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&!node.defaults.length&&!node.rest&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":71}],12:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}if(!spec.default&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":71,lodash:104}],13:[function(require,module,exports){var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(") ");print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.space();print(node.test)}this.push(";");if(node.update){this.space();print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.space();print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();print(node.handler);if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(") {");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.space();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");print.join(node.declarations,{separator:", "});if(!t.isFor(parent)){this.semicolon()}};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":71}],14:[function(require,module,exports){var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:104}],15:[function(require,module,exports){var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u007f-\uffff]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:104}],16:[function(require,module,exports){module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){var result;_.each(obj,function(fn,type){if(t["is"+type](node)){result=fn(node,parent);if(result!=null)return false}});return result};function Node(node,parent){this.parent=parent;this.node=node}Node.prototype.isUserWhitespacable=function(){return t.isUserWhitespacable(this.node)};Node.prototype.needsWhitespace=function(type){var parent=this.parent;var node=this.node;if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.prototype.needsWhitespaceBefore=function(){return this.needsWhitespace("before")};Node.prototype.needsWhitespaceAfter=function(){return this.needsWhitespace("after")};Node.prototype.needsParens=function(){var parent=this.parent;var node=this.node;if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){return t.isCallExpression(node)||_.some(node,function(val){return t.isCallExpression(val)})}return find(parens,node,parent)};_.each(Node.prototype,function(fn,key){Node[key]=function(node,parent){var n=new Node(node,parent);var args=_.toArray(arguments).slice(2);return n[key].apply(n,args)}})},{"../../types":71,"./parentheses":17,"./whitespace":18,lodash:104}],17:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.Binary=function(node,parent){if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.Literal=function(node,parent){if(_.isNumber(node.value)&&t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":71,lodash:104}],18:[function(require,module,exports){var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts))amounts={after:amounts,before:amounts};_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})},{"../../types":71,lodash:104}],19:[function(require,module,exports){module.exports=Position;var _=require("lodash");function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line++;self.column=0}else{self.column++}})};Position.prototype.unshift=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line--}else{self.column--}})}},{lodash:104}],20:[function(require,module,exports){module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":71,"source-map":112}],21:[function(require,module,exports){module.exports=Whitespace;var _=require("lodash");function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used=[]}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.start===token.start){startToken=tokens[i-1];endToken=token;return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.end===token.end){startToken=token;endToken=tokens[i+1];return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(!_.contains(this.used,line)){this.used.push(line);lines++}}return lines}},{lodash:104}],22:[function(require,module,exports){var t=require("./types"); var _=require("lodash");var types=require("ast-types");var def=types.Type.def;def("File").bases("Node").build("program").field("program",def("Program"));def("ParenthesizedExpression").bases("Expression").build("expression").field("expression",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));types.finalize();var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS)},{"./types":71,"ast-types":87,estraverse:99,lodash:104}],23:[function(require,module,exports){module.exports=AMDFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,CommonJSFormatter);AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];_.each(this.ids,function(id,name){names.push(t.literal(name))});names=t.arrayExpression(names);var params=_.values(this.ids);params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(!opts.amdModuleIds){return null}if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(.*?)$/,"");moduleName+=filenameRelative;return moduleName};AMDFormatter.prototype._push=function(node){var id=node.source.value;var ids=this.ids;if(ids[id]){return ids[id]}else{return this.ids[id]=this.file.generateUidIdentifier(id)}};AMDFormatter.prototype.import=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var id=specifier.id;if(specifier.default){id=t.identifier("default")}var ref;if(t.isImportBatchSpecifier(specifier)){ref=this._push(node)}else{ref=t.memberExpression(this._push(node),id,false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var self=this;return this._exportSpecifier(function(){return self._push(node)},specifier,node,nodes)}},{"../../types":71,"../../util":73,"./common":25,lodash:104}],24:[function(require,module,exports){module.exports=CommonJSInteropFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");function CommonJSInteropFormatter(file){this.file=file}util.inherits(CommonJSInteropFormatter,CommonJSFormatter);CommonJSInteropFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source.raw})]))]))}else{CommonJSFormatter.prototype.importSpecifier.apply(this,arguments)}}},{"../../types":71,"../../util":73,"./common":25}],25:[function(require,module,exports){module.exports=CommonJSFormatter;var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){this.file=file}CommonJSFormatter.prototype.import=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source.raw},true))};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=t.identifier("default")}var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source.raw,KEY:specifier.id}))};CommonJSFormatter.prototype.export=function(node,nodes){var declar=node.declaration;if(node.default){var ref=declar;if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}nodes.push(util.template("exports-default",{VALUE:ref},true))}else{var assign;if(t.isVariableDeclaration(declar)){var decl=declar.declarations[0];if(decl.init){decl.init=util.template("exports-assign",{VALUE:decl.init,KEY:decl.id})}nodes.push(declar)}else{assign=util.template("exports-assign",{VALUE:declar.id,KEY:declar.id},true);nodes.push(t.toStatement(declar));nodes.push(assign);if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}}}};CommonJSFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(util.template("exports-wildcard",{OBJECT:getRef()},true))}else{nodes.push(util.template("exports-assign-key",{VARIABLE_NAME:variableName.name,OBJECT:getRef(),KEY:specifier.id},true))}}else{nodes.push(util.template("exports-assign",{VALUE:specifier.id,KEY:variableName},true))}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){return this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../types":71,"../../util":73}],26:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.import=function(){};IgnoreFormatter.prototype.importSpecifier=function(){};IgnoreFormatter.prototype.export=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":71}],27:[function(require,module,exports){module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];_.each(this.ids,function(id,name){names.push(t.literal(name))});var ids=_.values(this.ids);var args=[t.identifier("exports")].concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.arrayExpression([t.literal("exports")].concat(names))];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_ARGUMENTS:names.map(function(name){return t.callExpression(t.identifier("require"),[name])})});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":71,"../../util":73,"./amd":23,lodash:104}],28:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform._ensureTransformerNames=function(type,keys){_.each(keys,function(key){if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}})};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),commonInterop:require("./modules/common-interop"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({modules:require("./transformers/es6-modules"),propertyNameShorthand:require("./transformers/es6-property-name-shorthand"),arrayComprehension:require("./transformers/es7-array-comprehension"),generatorComprehension:require("./transformers/es7-generator-comprehension"),arrowFunctions:require("./transformers/es6-arrow-functions"),classes:require("./transformers/es6-classes"),_propertyLiterals:require("./transformers/_property-literals"),computedPropertyNames:require("./transformers/es6-computed-property-names"),objectSpread:require("./transformers/es7-object-spread"),exponentiationOperator:require("./transformers/es7-exponentiation-operator"),spread:require("./transformers/es6-spread"),templateLiterals:require("./transformers/es6-template-literals"),propertyMethodAssignment:require("./transformers/es5-property-method-assignment"),defaultParameters:require("./transformers/es6-default-parameters"),restParameters:require("./transformers/es6-rest-parameters"),destructuring:require("./transformers/es6-destructuring"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),react:require("./transformers/react"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),generators:require("./transformers/es6-generators"),_blockHoist:require("./transformers/_block-hoist"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_memberExpressionKeywords:require("./transformers/_member-expression-keywords"),_moduleFormatter:require("./transformers/_module-formatter")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"./modules/amd":23,"./modules/common":25,"./modules/common-interop":24,"./modules/ignore":26,"./modules/umd":27,"./transformer":29,"./transformers/_alias-functions":30,"./transformers/_block-hoist":31,"./transformers/_declarations":32,"./transformers/_member-expression-keywords":33,"./transformers/_module-formatter":34,"./transformers/_property-literals":35,"./transformers/es5-property-method-assignment":36,"./transformers/es6-arrow-functions":37,"./transformers/es6-classes":38,"./transformers/es6-computed-property-names":39,"./transformers/es6-constants":40,"./transformers/es6-default-parameters":41,"./transformers/es6-destructuring":42,"./transformers/es6-for-of":43,"./transformers/es6-generators":48,"./transformers/es6-let-scoping":53,"./transformers/es6-modules":54,"./transformers/es6-property-name-shorthand":55,"./transformers/es6-rest-parameters":56,"./transformers/es6-spread":57,"./transformers/es6-template-literals":58,"./transformers/es6-unicode-regex":59,"./transformers/es7-abstract-references":60,"./transformers/es7-array-comprehension":61,"./transformers/es7-exponentiation-operator":62,"./transformers/es7-generator-comprehension":63,"./transformers/es7-object-spread":64,"./transformers/react":65,"./transformers/use-strict":66,lodash:104}],29:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer){this.transformer=Transformer.normalise(transformer);this.key=key}Transformer.normalise=function(transformer){if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_")return;if(_.isFunction(fns))fns={enter:fns};transformer[type]=fns});return transformer};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;var astRun=function(key){if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};astRun("enter");var build=function(exit){return function(node,parent,scope){var types=[node.type].concat(t.ALIAS_KEYS[node.type]||[]);var fns=transformer.all;_.each(types,function(type){fns=transformer[type]||fns});if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};traverse(ast,{enter:build(),exit:build(true)});astRun("exit")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;if(key[0]!=="_"){var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false}return true}},{"../traverse":67,"../types":71,lodash:104}],30:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var go=function(getBody,node,file,scope){var argumentsId;var thisId;var getArgumentsId=function(){return argumentsId=argumentsId||file.generateUidIdentifier("arguments",scope)};var getThisId=function(){return thisId=thisId||file.generateUidIdentifier("this",scope)};traverse(node,function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return false}if(node._ignoreAliasFunctions)return;var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=getArgumentsId}else if(t.isThisExpression(node)){getId=getThisId}else{return}if(t.isReferenced(node,parent))return getId()});return false});var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.identifier("this"))}};exports.Program=function(node,parent,file,scope){go(function(){return node.body},node,file,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,file,scope){go(function(){t.ensureBlock(node);return node.body.body},node,file,scope)}},{"../../traverse":67,"../../types":71}],31:[function(require,module,exports){exports.BlockStatement=exports.Program={exit:function(node){var unshift=[];node.body=node.body.filter(function(bodyNode){if(bodyNode._blockHoist){unshift.push(bodyNode);return false}else{return true}});node.body=unshift.concat(node.body)}}},{}],32:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BlockStatement=exports.Program=function(node){_.each(node._declarations,function(declar){node.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(declar.id,declar.init)]))})}},{"../../types":71,lodash:104}],33:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":71,esutils:103}],34:[function(require,module,exports){var transform=require("../transform");exports.ast={exit:function(ast,file){if(!transform.transformers.modules.canRun(file))return;if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../transform":28}],35:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&_.isString(key.value)&&esutils.keyword.isIdentifierName(key.value)){key.type="Identifier";key.name=key.value;delete key.value;node.computed=false}}},{"../../types":71,esutils:103,lodash:104}],36:[function(require,module,exports){var util=require("../../util");var _=require("lodash");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(_.isEmpty(mutatorMap))return;var objId=util.getUid(parent,file);return util.template("object-define-properties-closure",{KEY:objId,OBJECT:node,CONTENT:util.template("object-define-properties",{OBJECT:objId,PROPS:util.buildDefineProperties(mutatorMap)})})}},{"../../util":73,lodash:104}],37:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction=true;node.expression=false;node.type="FunctionExpression";return node}},{"../../types":71}],38:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ClassDeclaration=function(node,parent,file,scope){return t.variableDeclaration("let",[t.variableDeclarator(node.id,new Class(node,file,scope).run())])};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope).run()};var getMemberExpressionObject=function(node){while(t.isMemberExpression(node)){node=node.object}return node};function Class(node,file,scope){this.scope=scope;this.node=node;this.file=file;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superClassArgument=this.superName;var superClassCallee=this.superName;var superName=this.superName;var className=this.className;var file=this.file;if(superName){if(t.isMemberExpression(superName)){superClassArgument=superClassCallee=getMemberExpressionObject(superName)}else if(!t.isIdentifier(superName)){superClassArgument=superName;superClassCallee=superName=file.generateUidIdentifier("ref",this.scope)}}this.superName=superName;var container=util.template("class",{CLASS_NAME:className});var block=container.callee.expression.body;var body=this.body=block.body;var constructor=this.constructor=body[0].declarations[0].init;if(this.node.id)constructor.id=className;var returnStatement=body.pop();if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("extends"),[className,superName])));container.arguments.push(superClassArgument);container.callee.expression.params.push(superClassCallee)}this.buildBody();if(body.length===1){return constructor}else{body.push(returnStatement);return container}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;var self=this;_.each(classBody,function(node){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}});if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(!_.isEmpty(this.instanceMutatorMap)){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(!_.isEmpty(this.staticMutatorMap)){staticProps=util.buildDefineProperties(this.staticMutatorMap,className)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addDeclaration("class-props"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var mutatorMap=this.instanceMutatorMap;if(node.static)mutatorMap=this.staticMutatorMap;var kind=node.kind;if(kind===""){kind="value";util.pushMutatorMap(mutatorMap,methodName,"writable",t.identifier("true"))}util.pushMutatorMap(mutatorMap,methodName,kind,node)};Class.prototype.superIdentifier=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};Class.prototype.replaceInstanceSuperReferences=function(methodNode){var method=methodNode.value;var self=this;traverse(method,function(node,parent){if(t.isIdentifier(node,{name:"super"})){return self.superIdentifier(methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;callee.property=t.memberExpression(callee.property,t.identifier("call"));node.arguments.unshift(t.thisExpression())}})};Class.prototype.pushConstructor=function(method){if(method.kind!==""){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct.defaults=fn.defaults;construct.params=fn.params;construct.body=fn.body;construct.rest=fn.rest}},{"../../traverse":67,"../../types":71,"../../util":73,lodash:104}],39:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var computed=[];node.properties=node.properties.filter(function(prop){if(prop.computed){hasComputed=true;computed.unshift(prop);return false}else{return true}});if(!hasComputed)return;var objId=util.getUid(parent,file);var container=util.template("function-return-obj",{KEY:objId,OBJECT:node});var containerCallee=container.callee.expression;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;_.each(computed,function(prop){containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))});return container}},{"../../types":71,"../../util":73,lodash:104}],40:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var _=require("lodash");exports.Program=exports.BlockStatement=exports.ForInStatement=exports.ForOfStatement=exports.ForStatement=function(node,parent,file){var constants={};var check=function(parent,names){_.each(names,function(nameNode,name){if(!_.has(constants,name))return;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])return;throw file.errorWithNode(nameNode,name+" is read-only")})};var getIds=function(node){return t.getIds(node,true,["MemberExpression"])};_.each(node.body,function(child,parent){if(child&&t.isVariableDeclaration(child,{kind:"const"})){_.each(child.declarations,function(declar){_.each(getIds(declar),function(nameNode,name){var names={};names[name]=nameNode;check(parent,names);constants[name]=parent});declar._ignoreConstant=true});child._ignoreConstant=true;child.kind="let"}});if(_.isEmpty(constants))return;traverse(node,function(child,parent){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child))}})}},{"../../traverse":67,"../../types":71,lodash:104}],41:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.Function=function(node,parent,file,scope){if(!node.defaults||!node.defaults.length)return;t.ensureBlock(node);var ids=node.params.map(function(param){return t.getIds(param)});var closure=false;_.each(node.defaults,function(def,i){if(!def)return;var param=node.params[i];_.each(ids.slice(i),function(ids){var check=function(node,parent){if(!t.isIdentifier(node)||!t.isReferenced(node,parent))return;if(_.contains(ids,node.name)){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){closure=true}};check(def,node);traverse(def,check)});var has=scope.get(param.name);if(has&&!_.contains(node.params,has)){closure=true}});var body=[];_.each(node.defaults,function(def,i){if(!def)return;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))});if(closure){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}node.defaults=[]}},{"../../traverse":67,"../../types":71,"../../util":73,lodash:104}],42:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildVariableAssign=function(kind,id,init){if(kind===false){return t.expressionStatement(t.assignmentExpression("=",id,init))}else{return t.variableDeclaration(kind,[t.variableDeclarator(id,init)])}};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else if(t.isMemberExpression(elem)){nodes.push(buildVariableAssign(false,elem,parentId))}else{nodes.push(buildVariableAssign(opts.kind,elem,parentId))}};var pushObjectPattern=function(opts,nodes,pattern,parentId){_.each(pattern.properties,function(prop,i){if(t.isSpreadProperty(prop)){var keys=[];_.each(pattern.properties,function(prop2,i2){if(i2>=i)return false;if(t.isSpreadProperty(prop2))return;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)});keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addDeclaration("object-spread"),[parentId,keys]);nodes.push(buildVariableAssign(opts.kind,prop.argument,value))}else{var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts.kind,pattern2,patternId2))}}})};var pushArrayPattern=function(opts,nodes,pattern,parentId){var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,opts.file.toArray(parentId))]));parentId=_parentId;_.each(pattern.elements,function(elem,i){if(!elem)return;var newPatternId;if(t.isSpreadElement(elem)){newPatternId=opts.file.toArray(parentId);if(+i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)})};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var file=opts.file;var scope=opts.scope;if(!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,parentId)]));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,file,scope){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=file.generateUidIdentifier("ref",scope);node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,file,scope){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=file.generateUidIdentifier("ref",scope);pushPattern({kind:"var",nodes:nodes,pattern:pattern,id:parentId,file:file,scope:scope});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;var nodes=[];var ref=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({kind:false,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,file){if(parent.type==="ExpressionStatement")return;if(!t.isPattern(node.left))return;throw file.errorWithNode(node,"AssignmentExpression destructuring outside of a ExpressionStatement is forbidden due to current 6to5 limitations")};exports.VariableDeclaration=function(node,parent,file,scope){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var hasPattern=false;_.each(node.declarations,function(declar){if(t.isPattern(declar.id)){hasPattern=true;return false}});if(!hasPattern)return;_.each(node.declarations,function(declar){var patternId=declar.init;var pattern=declar.id;if(t.isPattern(pattern)&&patternId){pushPattern({kind:node.kind,nodes:nodes,pattern:pattern,id:patternId,file:file,scope:scope})}else{nodes.push(buildVariableAssign(node.kind,declar.id,declar.init))}});if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){var declar;_.each(nodes,function(node){declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)});return declar}return nodes}},{"../../types":71,lodash:104}],43:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ForOfStatement=function(node,parent,file,scope){var left=node.left;var declar;var stepKey=file.generateUidIdentifier("step",scope);var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var node2=util.template("for-of",{ITERATOR_KEY:file.generateUidIdentifier("iterator",scope),STEP_KEY:stepKey,OBJECT:node.right});t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":71,"../../util":73}],44:[function(require,module,exports){var assert=require("assert");var loc=require("../util").loc;var t=require("../../../../types");exports.ParenthesizedExpression=function(expr,path,explodeViaTempVar,finish){return finish(this.explodeExpression(path.get("expression")))};exports.MemberExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.memberExpression(this.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed))};exports.CallExpression=function(expr,path,explodeViaTempVar,finish){var oldCalleePath=path.get("callee");var newCallee=this.explodeExpression(oldCalleePath);if(!t.isMemberExpression(oldCalleePath.node)&&t.isMemberExpression(newCallee)){newCallee=t.sequenceExpression([t.literal(0),newCallee])}return finish(t.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.NewExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.ObjectExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.objectExpression(path.get("properties").map(function(propPath){return t.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value"))) })))};exports.ArrayExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})))};exports.SequenceExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var lastIndex=expr.expressions.length-1;var self=this;var result;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result};exports.LogicalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var after=loc();var result;if(!ignoreResult){result=this.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){this.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");this.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);this.mark(after);return result};exports.ConditionalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var elseLoc=loc();var after=loc();var test=this.explodeExpression(path.get("test"));var result;this.jumpIfNot(test,elseLoc);if(!ignoreResult){result=this.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);this.jump(after);this.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);this.mark(after);return result};exports.UnaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.unaryExpression(expr.operator,this.explodeExpression(path.get("argument")),!!expr.prefix))};exports.BinaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))))};exports.AssignmentExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.assignmentExpression(expr.operator,this.explodeExpression(path.get("left")),this.explodeExpression(path.get("right"))))};exports.UpdateExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.updateExpression(expr.operator,this.explodeExpression(path.get("argument")),expr.prefix))};exports.YieldExpression=function(expr,path){var after=loc();var arg=expr.argument&&this.explodeExpression(path.get("argument"));var result;if(arg&&expr.delegate){result=this.makeTempVar();this.emit(t.returnStatement(t.callExpression(this.contextProperty("delegateYield"),[arg,t.literal(result.property.name),after])));this.mark(after);return result}this.emitAssign(this.contextProperty("next"),after);this.emit(t.returnStatement(arg||null));this.mark(after);return this.contextProperty("sent")}},{"../../../../types":71,"../util":51,assert:89}],45:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var util=require("../util");var t=require("../../../../types");var runtimeKeysMethod=util.runtimeProperty("keys");var loc=util.loc;exports.ExpressionStatement=function(path){this.explodeExpression(path.get("expression"),true)};exports.LabeledStatement=function(path,stmt){this.explodeStatement(path.get("body"),stmt.label)};exports.WhileStatement=function(path,stmt,labelId){var before=loc();var after=loc();this.mark(before);this.jumpIfNot(this.explodeExpression(path.get("test")),after);this.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(before);this.mark(after)};exports.DoWhileStatement=function(path,stmt,labelId){var first=loc();var test=loc();var after=loc();this.mark(first);this.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){this.explode(path.get("body"))});this.mark(test);this.jumpIf(this.explodeExpression(path.get("test")),first);this.mark(after)};exports.ForStatement=function(path,stmt,labelId){var head=loc();var update=loc();var after=loc();if(stmt.init){this.explode(path.get("init"),true)}this.mark(head);if(stmt.test){this.jumpIfNot(this.explodeExpression(path.get("test")),after)}else{}this.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){this.explodeStatement(path.get("body"))});this.mark(update);if(stmt.update){this.explode(path.get("update"),true)}this.jump(head);this.mark(after)};exports.ForInStatement=function(path,stmt,labelId){t.assertIdentifier(stmt.left);var head=loc();var after=loc();var keyIterNextFn=this.makeTempVar();this.emitAssign(keyIterNextFn,t.callExpression(runtimeKeysMethod,[this.explodeExpression(path.get("right"))]));this.mark(head);var keyInfoTmpVar=this.makeTempVar();this.jumpIf(t.memberExpression(t.assignmentExpression("=",keyInfoTmpVar,t.callExpression(keyIterNextFn,[])),t.identifier("done"),false),after);this.emitAssign(stmt.left,t.memberExpression(keyInfoTmpVar,t.identifier("value"),false));this.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(head);this.mark(after)};exports.BreakStatement=function(path,stmt){this.emitAbruptCompletion({type:"break",target:this.leapManager.getBreakLoc(stmt.label)})};exports.ContinueStatement=function(path,stmt){this.emitAbruptCompletion({type:"continue",target:this.leapManager.getContinueLoc(stmt.label)})};exports.SwitchStatement=function(path,stmt){var disc=this.emitAssign(this.makeTempVar(),this.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var self=this;var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];t.assertSwitchCase(c);if(c.test){condition=t.conditionalExpression(t.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}this.jump(this.explodeExpression(new types.NodePath(condition,path,"discriminant")));this.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});this.mark(after);if(defaultLoc.value===-1){this.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}};exports.IfStatement=function(path,stmt){var elseLoc=stmt.alternate&&loc();var after=loc();this.jumpIfNot(this.explodeExpression(path.get("test")),elseLoc||after);this.explodeStatement(path.get("consequent"));if(elseLoc){this.jump(after);this.mark(elseLoc);this.explodeStatement(path.get("alternate"))}this.mark(after)};exports.ReturnStatement=function(path){this.emitAbruptCompletion({type:"return",value:this.explodeExpression(path.get("argument"))})};exports.TryStatement=function(path,stmt){var after=loc();var self=this;var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(this.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);this.tryEntries.push(tryEntry);this.updateContextPrevLoc(tryEntry.firstLoc);this.leapManager.withEntry(tryEntry,function(){this.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){this.jump(finallyLoc)}else{this.jump(after)}this.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=this.makeTempVar();this.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;t.assertCatchClause(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(path.value.name===catchParamName&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)}});this.leapManager.withEntry(catchEntry,function(){this.explodeStatement(bodyPath)})}if(finallyLoc){this.updateContextPrevLoc(this.mark(finallyLoc));this.leapManager.withEntry(finallyEntry,function(){this.explodeStatement(path.get("finalizer"))});this.emit(t.callExpression(this.contextProperty("finish"),[finallyEntry.firstLoc]))}});this.mark(after)};exports.ThrowStatement=function(path){this.emit(t.throwStatement(this.explodeExpression(path.get("argument"))))}},{"../../../../types":71,"../leap":49,"../util":51,assert:89,"ast-types":87}],46:[function(require,module,exports){exports.Emitter=Emitter;var explodeExpressions=require("./explode-expressions");var explodeStatements=require("./explode-statements");var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var meta=require("../meta");var util=require("../util");var t=require("../../../../types");var _=require("lodash");var loc=util.loc;var n=types.namedTypes;function Emitter(contextId){assert.ok(this instanceof Emitter);t.assertIdentifier(contextId);this.contextId=contextId;this.listing=[];this.marked=[true];this.finalLoc=loc();this.tryEntries=[];this.leapManager=new leap.LeapManager(this)}Emitter.prototype.mark=function(loc){t.assertLiteral(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Emitter.prototype.emit=function(node){if(t.isExpression(node))node=t.expressionStatement(node);t.assertStatement(node);this.listing.push(node)};Emitter.prototype.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Emitter.prototype.assign=function(lhs,rhs){return t.expressionStatement(t.assignmentExpression("=",lhs,rhs))};Emitter.prototype.contextProperty=function(name,computed){return t.memberExpression(this.contextId,computed?t.literal(name):t.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Emitter.prototype.isVolatileContextProperty=function(expr){if(t.isMemberExpression(expr)){if(expr.computed){return true}if(t.isIdentifier(expr.object)&&t.isIdentifier(expr.property)&&expr.object.name===this.contextId.name&&_.has(volatileContextPropertyNames,expr.property.name)){return true}}return false};Emitter.prototype.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Emitter.prototype.setReturnValue=function(valuePath){t.assertExpression(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Emitter.prototype.clearPendingException=function(tryLoc,assignee){t.assertLiteral(tryLoc);var catchCall=t.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Emitter.prototype.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(t.breakStatement())};Emitter.prototype.jumpIf=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);this.emit(t.ifStatement(test,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};Emitter.prototype.jumpIfNot=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);var negatedTest;if(t.isUnaryExpression(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=t.unaryExpression("!",test)}this.emit(t.ifStatement(negatedTest,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};var nextTempId=0;Emitter.prototype.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Emitter.prototype.getContextFunction=function(id){var node=t.functionExpression(id||null,[this.contextId],t.blockStatement([this.getDispatchLoop()]),false,false);node._aliasFunction=true;return node};Emitter.prototype.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(t.switchCase(t.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(t.switchCase(this.finalLoc,[]),t.switchCase(t.literal("end"),[t.returnStatement(t.callExpression(this.contextProperty("stop"),[]))]));return t.whileStatement(t.literal(true),t.switchStatement(t.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return t.isBreakStatement(stmt)||t.isContinueStatement(stmt)||t.isReturnStatement(stmt)||t.isThrowStatement(stmt)}Emitter.prototype.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return t.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return t.arrayExpression(triple)}))};Emitter.prototype.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.check(node);if(t.isStatement(node))return self.explodeStatement(path);if(t.isExpression(node))return self.explodeExpression(path,ignoreResult);if(t.isDeclaration(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Emitter.prototype.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;t.assertStatement(stmt);if(labelId){t.assertIdentifier(labelId)}else{labelId=null}if(t.isBlockStatement(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}var fn=explodeStatements[stmt.type];if(fn){fn.call(this,path,stmt,labelId)}else{throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Emitter.prototype.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[t.literal(record.type)];if(record.type==="break"||record.type==="continue"){t.assertLiteral(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){t.assertExpression(record.value);abruptArgs[1]=record.value}}this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!_.has(record,"target")}if(type==="break"||type==="continue"){return!_.has(record,"value")&&t.isLiteral(record.target)}if(type==="return"||type==="throw"){return _.has(record,"value")&&!_.has(record,"target")}return false}Emitter.prototype.getUnmarkedCurrentLoc=function(){return t.literal(this.listing.length)};Emitter.prototype.updateContextPrevLoc=function(loc){if(loc){t.assertLiteral(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Emitter.prototype.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){t.assertExpression(expr)}else{return expr}var self=this;function finish(expr){t.assertExpression(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}var fn=explodeExpressions[expr.type];if(fn){return fn.call(this,expr,path,explodeViaTempVar,finish,ignoreResult)}else{throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"../../../../types":71,"../leap":49,"../meta":50,"../util":51,"./explode-expressions":44,"./explode-statements":45,assert:89,"ast-types":87,lodash:104}],47:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var t=require("../../../types");var _=require("lodash");exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);t.assertFunction(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){t.assertVariableDeclaration(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(t.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return t.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return t.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(t.isVariableDeclaration(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(t.isVariableDeclaration(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var assignment=t.expressionStatement(t.assignmentExpression("=",node.id,t.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(t.isBlockStatement(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(t.isIdentifier(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!_.has(paramNames,name)){declarations.push(t.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return t.variableDeclaration("var",declarations)}},{"../../../types":71,assert:89,"ast-types":87,lodash:104}],48:[function(require,module,exports){module.exports=require("./visit").transform},{"./visit":52}],49:[function(require,module,exports){exports.FunctionEntry=FunctionEntry;exports.FinallyEntry=FinallyEntry;exports.SwitchEntry=SwitchEntry;exports.LeapManager=LeapManager;exports.CatchEntry=CatchEntry;exports.LoopEntry=LoopEntry;exports.TryEntry=TryEntry;var assert=require("assert");var util=require("util");var t=require("../../../types");var inherits=util.inherits;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);t.assertLiteral(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);t.assertLiteral(breakLoc);t.assertLiteral(continueLoc);if(label){t.assertIdentifier(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);function SwitchEntry(breakLoc){Entry.call(this);t.assertLiteral(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);t.assertLiteral(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);function CatchEntry(firstLoc,paramId){Entry.call(this);t.assertLiteral(firstLoc);t.assertIdentifier(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);function FinallyEntry(firstLoc){Entry.call(this);t.assertLiteral(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}LeapManager.prototype.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LeapManager.prototype._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else{return loc}}}return null};LeapManager.prototype.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LeapManager.prototype.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"../../../types":71,"./emit":46,assert:89,util:98}],50:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var m=require("private").makeAccessor();var _=require("lodash");var isArray=types.builtInTypes.array;var n=types.namedTypes;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.check(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.check(node);var meta=m(node);if(_.has(meta,propertyName))return meta[propertyName];if(_.has(opaqueTypes,node.type))return meta[propertyName]=false;if(_.has(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(_.has(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:89,"ast-types":87,lodash:104,"private":105}],51:[function(require,module,exports){var t=require("../../../types");exports.runtimeProperty=function(name){return t.memberExpression(t.identifier("regeneratorRuntime"),t.identifier(name))};exports.loc=function(){return t.literal(-1)}},{"../../../types":71}],52:[function(require,module,exports){var runtimeProperty=require("./util").runtimeProperty;var Emitter=require("./emit").Emitter;var hoist=require("./hoist").hoist;var types=require("ast-types");var t=require("../../../types");var runtimeAsyncMethod=runtimeProperty("async");var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");exports.transform=function transform(node,file){return types.visit(node,{visitFunction:function(path){return visitor.call(this,path,file)}})};var visitor=function(path,file){this.traverse(path);var node=path.value;var scope;if(!node.generator&&!node.async){return}node.generator=false;if(node.expression){node.expression=false;node.body=t.blockStatement([t.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=file.generateUidIdentifier("callee",scope));var innerFnId=t.identifier(node.id.name+"$");var contextId=file.generateUidIdentifier("context$",scope);var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),node.async?t.literal(null):outerFnId,t.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=t.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(t.returnStatement(wrapCall));node.body=t.blockStatement(outerBody);if(node.async){node.async=false;return}if(t.isFunctionDeclaration(node)){var pp=path.parent;while(pp&&!(t.isBlockStatement(pp.value)||t.isProgram(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=t.variableDeclaration("var",[t.variableDeclarator(node.id,t.callExpression(runtimeMarkMethod,[node]))]);t.inheritsComments(varDecl,node);t.removeComments(node);varDecl._blockHoist=true;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;for(var i=0;i<bodyLen;++i){var firstStmtPath=bodyPath.get(i);if(!shouldNotHoistAbove(firstStmtPath)){firstStmtPath.insertBefore(varDecl);return}}bodyPath.push(varDecl)}else{t.assertFunctionExpression(node);return t.callExpression(runtimeMarkMethod,[node])}};function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;t.assertStatement(value);if(t.isExpressionStatement(value)&&t.isLiteral(value.expression)&&value.expression.value==="use strict"){return true}if(t.isVariableDeclaration(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(t.isCallExpression(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(){return false},visitAwaitExpression:function(path){return t.yieldExpression(path.value.argument,false)}})},{"../../../types":71,"./emit":46,"./hoist":47,"./util":51,"ast-types":87}],53:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;node._let=true;node.kind="var";return true};var isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node)};var standardiseLets=function(declars){_.each(declars,function(declar){delete declar._let})};exports.VariableDeclaration=function(node){isLet(node)};exports.For=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init)){t.ensureBlock(node);node.body._letDeclars=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,file,scope);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.BlockStatement=function(block,parent,file,scope){if(!t.isFor(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(forParent,block,parent,file,scope){this.forParent=forParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.letReferences={};this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;this.info=this.getInfo();this.remap();if(t.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var referencesInClosure=this.getLetReferences();if(!referencesInClosure)return this.noClosure();this.has=this.checkFor();this.hoistVarDeclarations();standardiseLets(this.info.declarators);var letReferences=_.values(this.letReferences);var fn=t.functionExpression(null,letReferences,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var params=this.getParams(letReferences);var call=t.callExpression(fn,params);var ret=this.file.generateUidIdentifier("ret",this.scope);var hasYield=traverse.hasType(fn.body,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}this.build(ret,call)};LetScoping.prototype.noClosure=function(){standardiseLets(this.info.declarators)};LetScoping.prototype.remap=function(){var replacements=this.info.duplicates;var block=this.block;if(_.isEmpty(replacements))return;var replace=function(node,parent,scope){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope&&scope.hasOwn(node.name))return;node.name=replacements[node.name]||node.name};var traverseReplace=function(node,parent){replace(node,parent);traverse(node,replace)};var forParent=this.forParent;if(forParent){traverseReplace(forParent.right,forParent);traverseReplace(forParent.test,forParent);traverseReplace(forParent.update,forParent)}traverse(block,replace)};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope)}};_.each(opts.declarators,function(declar){opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=_.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)});_.each(block.body,function(declar){if(!isLet(declar))return;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})});return opts};LetScoping.prototype.checkFor=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};var forParent=this.forParent;traverse(this.block,function(node){var replace;if(t.isFunction(node)||t.isFor(node)){return false}if(forParent&&node&&!node.label){if(t.isBreakStatement(node)){has.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){has.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){has.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)});return has};LetScoping.prototype.hoistVarDeclarations=function(){var self=this;traverse(this.block,function(node){if(t.isForStatement(node)){if(isVar(node.init)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left)){node.left=node.left.declarations[0].id}}else if(isVar(node)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return false}})};LetScoping.prototype.getParams=function(params){var info=this.info;params=_.cloneDeep(params);_.each(params,function(param){param.name=info.duplicates[param.name]||param.name});return params};LetScoping.prototype.getLetReferences=function(){var closurify=false;var self=this;traverse(this.block,function(node,parent,scope){if(t.isFunction(node)){traverse(node,function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope.hasOwn(node.name))return;closurify=true;if(!_.contains(self.info.outsideKeys,node.name))return;self.letReferences[node.name]=node});return false}else if(t.isFor(node)){return false}});return closurify};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];_.each(node.declarations,function(declar){if(!declar.init)return;var expr=t.assignmentExpression("=",declar.id,declar.init); replace.push(t.inherits(expr,declar))});return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var forParent=this.forParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){var label=forParent.label=forParent.label||this.file.generateUidIdentifier("loop",this.scope);if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../traverse":67,"../../types":71,"../../util":73,lodash:104}],54:[function(require,module,exports){var _=require("lodash");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){_.each(node.specifiers,function(specifier){file.moduleFormatter.importSpecifier(specifier,node,nodes)})}else{file.moduleFormatter.import(node,nodes)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){file.moduleFormatter.export(node,nodes)}else{_.each(node.specifiers,function(specifier){file.moduleFormatter.exportSpecifier(specifier,node,nodes)})}return nodes}},{lodash:104}],55:[function(require,module,exports){exports.Property=function(node){if(node.shorthand)node.shorthand=false}},{}],56:[function(require,module,exports){var t=require("../../types");exports.Function=function(node,parent,file){if(!node.rest)return;var rest=node.rest;delete node.rest;t.ensureBlock(node);var call=t.callExpression(file.addDeclaration("arguments-to-array"),[t.identifier("arguments")]);if(node.params.length){call=t.callExpression(t.memberExpression(call,t.identifier("slice")),[t.literal(node.params.length)])}call._ignoreAliasFunctions=true;node.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(rest,call)]))}},{"../../types":71}],57:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){var has=false;_.each(nodes,function(node){if(t.isSpreadElement(node)){has=true;return false}});return has};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};_.each(props,function(prop){if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}});push();return nodes};exports.ArrayExpression=function(node,parent,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes=build(args,file);var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(callee.computed){callee.object=t.memberExpression(callee.object,callee.property,true);callee.property=t.identifier("apply");callee.computed=false}else{callee.property=t.memberExpression(callee.property,t.identifier("apply"))}}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var nodes=build(args,file);var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}return t.callExpression(file.addDeclaration("apply-constructor"),[node.callee,args])}},{"../../types":71,lodash:104}],58:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];_.each(quasi.quasis,function(elem){strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))});args.push(t.callExpression(file.addDeclaration("tagged-template-literal"),[t.arrayExpression(strings),t.arrayExpression(raw)]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];_.each(node.quasis,function(elem){nodes.push(t.literal(elem.value.raw));var expr=node.expressions.shift();if(expr){if(t.isBinary(expr))expr=t.parenthesizedExpression(expr);nodes.push(expr)}});if(nodes.length>1){var last=_.last(nodes);if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());_.each(nodes,function(node){root=buildBinaryExpression(root,node)});return root}else{return nodes[0]}}},{"../../types":71,lodash:104}],59:[function(require,module,exports){var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(!_.contains(regex.flags,"u"))return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:104,"regexpu/rewrite-pattern":111}],60:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var container=function(parent,call,ret){if(t.isExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,file,scope){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){if(!t.isIdentifier(value)){var tempName=file.generateUid("temp");temp=value=t.identifier(tempName);scope.push(tempName,temp)}}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value)};exports.UnaryExpression=function(node,parent){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true))};exports.CallExpression=function(node,parent,file,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp;if(!t.isIdentifier(callee.object)){var tempName=file.generateUid("temp");temp=t.identifier(tempName);scope.push(tempName,temp)}var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})}},{"../../types":71,"../../util":73}],61:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");var single=function(node,file){var block=node.blocks[0];var templateName="array-expression-comprehension-map";if(node.filter)templateName="array-expression-comprehension-filter";var result=util.template(templateName,{STATEMENT:node.body,FILTER:node.filter,ARRAY:file.toArray(block.right),KEY:block.left});_.each([result.callee.object,result],function(call){if(t.isCallExpression(call)){call.arguments[0]._aliasFunction=true}});return result};var multiple=function(node,file){var uid=file.generateUidIdentifier("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee.expression._aliasFunction=true;var block=container.callee.expression.body;var body=block.body;var returnStatement=body.pop();body.push(exports._build(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container};exports._build=function(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=exports._build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("var",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))};exports.ComprehensionExpression=function(node,parent,file){if(node.generator)return;if(node.blocks.length===1){return single(node,file)}else{return multiple(node,file)}}},{"../../types":71,"../../util":73,lodash:104}],62:[function(require,module,exports){var t=require("../../types");var pow=t.memberExpression(t.identifier("Math"),t.identifier("pow"));exports.AssignmentExpression=function(node){if(node.operator!=="**=")return;node.operator="=";node.right=t.callExpression(pow,[node.left,node.right])};exports.BinaryExpression=function(node){if(node.operator!=="**")return;return t.callExpression(pow,[node.left,node.right])}},{"../../types":71}],63:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":71,"./es7-array-comprehension":61}],64:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node){var hasSpread=false;_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){hasSpread=true;return false}});if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}});push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("assign")),args)}},{"../../types":71,lodash:104}],65:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.XJSIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.XJSNamespacedName=function(node,parent,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.XJSMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.XJSExpressionContainer=function(node){return node.expression};exports.XJSAttribute={exit:function(node){var value=node.value||t.literal(true);return t.property("init",node.name,value)}};exports.XJSOpeningElement={exit:function(node){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(tagName&&(/[a-z]/.exec(tagName[0])||_.contains(tagName,"-"))){args.push(t.literal(tagName))}else{args.push(tagExpr)}var props=node.attributes;if(props.length){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(props.length){var prop=props.shift();if(t.isXJSSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){props=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}props=t.callExpression(t.memberExpression(t.identifier("React"),t.identifier("__spread")),objs)}}else{props=t.literal(null)}args.push(props);tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"));return t.callExpression(tagExpr,args)}};exports.XJSElement={exit:function(node){var callExpr=node.openingElement;_.each(node.children,function(child){if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);_.each(lines,function(line,i){var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){callExpr.arguments.push(t.literal(trimmedLine))}});return}callExpr.arguments.push(child)});return t.inherits(callExpr,node)}};var addDisplayName=function(id,call){if(!call||!t.isCallExpression(call))return;var callee=call.callee;if(!t.isMemberExpression(callee))return;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return;var args=call.arguments;if(args.length!==1)return;var first=args[0];if(!t.isObjectExpression(first))return;var props=first.properties;var safe=true;_.each(props,function(prop){if(t.isIdentifier(prop.key,{name:"displayName"})){return safe=false}});if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../types":71,esutils:103,lodash:104}],66:[function(require,module,exports){var t=require("../../types");module.exports=function(ast){var body=ast.program.body;var first=body[0];var noStrict=!first||!t.isExpressionStatement(first)||!t.isLiteral(first.expression)||first.expression.value!=="use strict";if(noStrict){body.unshift(t.expressionStatement(t.literal("use strict")))}}},{"../../types":71}],67:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,callbacks,opts){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,callbacks,opts)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};if(_.isArray(opts))opts={blacklist:opts};var blacklistTypes=opts.blacklist||[];if(_.isFunction(callbacks))callbacks={enter:callbacks};for(var i in keys){var key=keys[i];var nodes=parent[key];if(!nodes)continue;var updated=false;var handle=function(obj,key){var node=obj[key];if(!node)return;if(blacklistTypes.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result!=null){updated=true;node=obj[key]=result}};var opts2={scope:opts.scope,blacklist:opts.blacklist};if(t.isScope(node))opts2.scope=new Scope(node,opts.scope);if(callbacks.enter){var result=callbacks.enter(node,parent,opts2.scope);maybeReplace(result);if(result===false)return}traverse(node,callbacks,opts2);if(callbacks.exit){maybeReplace(callbacks.exit(node,parent,opts2.scope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated)parent[key]=_.flatten(parent[key])}else{handle(parent,key)}}}traverse.removeProperties=function(tree){var clear=function(node){delete node._scopeReferences;delete node._declarations;delete node.extendedRange;delete node._parent;delete node._scope;delete node.tokens;delete node.range;delete node.start;delete node.end;delete node.loc;delete node.raw;clearComments(node.trailingComments);clearComments(node.leadingComments)};var clearComments=function(comments){_.each(comments,clear)};clear(tree);traverse(tree,clear);return tree};traverse.hasType=function(tree,type,blacklistTypes){blacklistTypes=[].concat(blacklistTypes||[]);var has=false;if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;traverse(tree,function(node){if(node.type===type){has=true;return false}},{blacklist:blacklistTypes});return has}},{"../types":71,"./scope":68,lodash:104}],68:[function(require,module,exports){module.exports=Scope;var traverse=require("./index");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parent){this.parent=parent;this.block=block;this.references=this.getReferences()}Scope.prototype.getReferences=function(){var block=this.block;if(block._scopeReferences)return block._scopeReferences;var self=this;var references=block._scopeReferences={};var add=function(node){self.add(node,references)};if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isLet(node))add(node)});block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){_.each(block.body,function(node){if(t.isLet(node))add(node)})}if(t.isCatchClause(block)){add(block.param)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,function(node,parent,scope){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))add(declar)})}if(t.isFunction(node))return false;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}},{scope:this})}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return references};Scope.prototype.push=function(name,id,init){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[name]={id:id,init:init}}else{throw new Error("wtf")}};Scope.prototype.add=function(node,references){if(!node)return;_.merge(references||this.references,t.getIds(node,true))};Scope.prototype.get=function(id){return id&&(this.getOwn(id)||this.parentGet(id))};Scope.prototype.getOwn=function(id){return _.has(this.references,id)&&this.references[id]};Scope.prototype.parentGet=function(id){return this.parent&&this.parent.get(id)};Scope.prototype.has=function(id){return id&&(this.hasOwn(id)||this.parentHas(id))};Scope.prototype.hasOwn=function(id){return!!this.getOwn(id)};Scope.prototype.parentHas=function(id){return this.parent&&this.parent.has(id)}},{"../types":71,"./index":67,lodash:104}],69:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary"],BinaryExpression:["Binary"],UnaryExpression:["UnaryLike"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class"],ForOfStatement:["Statement","For","Scope"],ForInStatement:["Statement","For","Scope"],ForStatement:["Statement","For","Scope"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],70:[function(require,module,exports){module.exports={ArrayExpression:["elements"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],YieldExpression:["argument","delegate"]}},{}],71:[function(require,module,exports){var _=require("lodash");var t=exports;var addAssert=function(type,is){t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}};t.VISITOR_KEYS=require("./visitor-keys");_.each(t.VISITOR_KEYS,function(keys,type){var is=t["is"+type]=function(node,opts){return node&&node.type===type&&t.shallowEqual(node,opts)};addAssert(type,is)});t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node={type:type};_.each(keys,function(key,i){node[key]=args[i]});return node}});t.ALIAS_KEYS=require("./alias-keys");var _aliases={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=_aliases[alias]=_aliases[alias]||[];types.push(type)})});_.each(_aliases,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&_.contains(types,node.type)&&t.shallowEqual(node,opts)};addAssert(type,is)});t.isExpression=function(node){return!t.isStatement(node)};addAssert("Expression",t.isExpression);t.shallowEqual=function(actual,expected){var same=true;if(expected){_.each(expected,function(val,key){if(actual[key]!==val){return same=false}})}return same};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name.replace(/[^a-zA-Z0-9]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});return name};t.ensureBlock=function(node){node.body=t.toBlock(node.body,node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(!_.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKey=t.getIds.nodes[id.type];var arrKey=t.getIds.arrays[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKey){if(id[nodeKey])search.push(id[nodeKey])}else if(arrKey){search=search.concat(id[arrKey]||[])}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"id",ExportSpecifier:"id",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",ParenthesizedExpression:"expression",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:"specifiers",ImportDeclaration:"specifiers",VariableDeclaration:"declarations",ArrayPattern:"elements",ObjectPattern:"properties"};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.removeComments=function(child){delete child.leadingComments;delete child.trailingComments;return child};t.inheritsComments=function(child,parent){child.leadingComments=_.compact([].concat(child.leadingComments,parent.leadingComments));child.trailingComments=_.compact([].concat(child.trailingComments,parent.trailingComments));return child};t.removeComments=function(node){delete node.leadingComments;delete node.trailingComments};t.inherits=function(child,parent){child.loc=parent.loc;child.end=parent.end;child.range=parent.range;child.start=parent.start;t.inheritsComments(child,parent);return child};t.getSpecifierName=function(specifier){return specifier.name||specifier.id}},{"./alias-keys":69,"./builder-keys":70,"./visitor-keys":72,lodash:104}],72:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"],YieldExpression:["argument"]}},{}],73:[function(require,module,exports){(function(Buffer,__dirname){require("./patch");var estraverse=require("estraverse");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||[".js",".jsx",".es6"];var ext=path.extname(filename);return _.contains(exts,ext)};exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp;if(_.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val||"");if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(_.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.getUid=function(parent,file){var node;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}var id="ref";if(t.isIdentifier(node))id=node.name;return file.generateUidIdentifier(id)};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(method.computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(method.computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){var newNode=nodes[node.name];if(_.isString(newNode)){node.name=newNode}else{return newNode}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){node=node.expression; if(t.isParenthesizedExpression(node))node=node.expression}return node};exports.codeFrame=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+exports.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=exports.repeat(gutter.length-2);str+="|"+exports.repeat(colNumber)+"^"}return str}).join("\n")};exports.repeat=function(width,cha){cha=cha||" ";return new Array(width+1).join(cha)};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowReturnOutsideFunction:true,preserveParens:true,ecmaVersion:opts.experimental?7:6,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=t.file(ast,comments,tokens);traverse(ast,function(node,parent){node._parent=parent});if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=exports.codeFrame(code,loc.line,loc.column);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://githut.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":122,"./patch":22,"./traverse":67,"./types":71,"acorn-6to5":1,buffer:90,estraverse:99,fs:88,lodash:104,path:95,util:98}],74:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Node").field("type",isString).field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp))},{"../lib/shared":85,"../lib/types":86}],75:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":86,"./core":74}],76:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Function"));def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("id").field("id",def("Identifier"));def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":85,"../lib/types":86,"./core":74}],77:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":85,"../lib/types":86,"./core":74}],78:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("TypeAnnotatedIdentifier").bases("Pattern").build("annotation","identifier").field("annotation",def("TypeAnnotation")).field("identifier",def("Identifier"));def("TypeAnnotation").bases("Pattern").build("annotatedType","templateTypes","paramTypes","returnType","unionType","nullable").field("annotatedType",def("Identifier")).field("templateTypes",or([def("TypeAnnotation")],null)).field("paramTypes",or([def("TypeAnnotation")],null)).field("returnType",or(def("TypeAnnotation"),null)).field("unionType",or(def("TypeAnnotation"),null)).field("nullable",isBoolean);def("ObjectTypeAnnotation").bases("Pattern").build("properties","nullable").field("properties",[def("Property")]).field("nullable",isBoolean);def("VoidTypeAnnotation").bases("Pattern");def("ParametricTypeAnnotation").bases("Pattern").build("params").field("params",[def("Identifier")]);def("OptionalParameter").bases("Pattern").build("identifier").field("identifier",def("Identifier"));def("Identifier").field("annotation",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]);def("Function").field("returnType",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]).field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"]);def("ClassProperty").field("id",or(def("Identifier"),def("TypeAnnotatedIdentifier")));def("ClassDeclaration").field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"])},{"../lib/shared":85,"../lib/types":86,"./core":74}],79:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":85,"../lib/types":86,"./core":74}],80:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":87,assert:89}],81:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true); if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":83,"./scope":84,"./types":86,assert:89,util:98}],82:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this)}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){var visitor=PathVisitor.fromMethodsObject(methods);if(node instanceof NodePath){visitor.visit(node);return node.value}var rootPath=new NodePath({root:node});visitor.visit(rootPath.get("root"));return rootPath.value.root};var PVp=PathVisitor.prototype;PVp.visit=function(path){if(this instanceof this.Context){return this.visitor.visit(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visit,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visit(childPaths[i])}}}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName)};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};module.exports=PathVisitor},{"./node-path":81,"./types":86,assert:89}],83:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":86,assert:89}],84:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":81,"./types":86,assert:89}],85:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":86}],86:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:89}],87:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":74,"./def/e4x":75,"./def/es6":76,"./def/es7":77,"./def/fb-harmony":78,"./def/mozilla":79,"./lib/equiv":80,"./lib/node-path":81,"./lib/path-visitor":82,"./lib/types":86}],88:[function(require,module,exports){},{}],89:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual) }};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":98}],90:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;if(end<start)throw new TypeError("sourceEnd < sourceStart");if(target_start<0||target_start>=target.length)throw new TypeError("targetStart out of bounds");if(start<0||start>=source.length)throw new TypeError("sourceStart out of bounds");if(end<0||end>source.length)throw new TypeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new TypeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new TypeError("start out of bounds");if(end<0||end>this.length)throw new TypeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":91,ieee754:92,"is-array":93}],91:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],92:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],93:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],94:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],95:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:96}],96:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],97:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],98:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg) }}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":97,_process:96,inherits:94}],99:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.0";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller})},{}],100:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],101:[function(require,module,exports){(function(){"use strict";var Regex;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],102:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":101}],103:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":100,"./code":101,"./keyword":102}],104:[function(require,module,exports){(function(global){(function(){var undefined;var arrayPool=[],objectPool=[];var idCounter=0;var keyPrefix=+new Date+"";var largeArraySize=75;var maxPoolSize=40;var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reInterpolate=/<%=([\s\S]+?)%>/g;var reLeadingSpacesAndZeros=RegExp("^["+whitespace+"]*0+(?=.$)");var reNoMatch=/($^)/;var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\t\u2028\u2029\\]/g;var contextProps=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var templateCounter=0;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var cloneableClasses={};cloneableClasses[funcClass]=false;cloneableClasses[argsClass]=cloneableClasses[arrayClass]=cloneableClasses[boolClass]=cloneableClasses[dateClass]=cloneableClasses[numberClass]=cloneableClasses[objectClass]=cloneableClasses[regexpClass]=cloneableClasses[stringClass]=true;var debounceOptions={leading:false,maxWait:0,trailing:false};var descriptor={configurable:false,enumerable:false,value:null,writable:false};var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window||this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module; var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;var freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}function baseIndexOf(array,value,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0;while(++index<length){if(array[index]===value){return index}}return-1}function cacheIndexOf(cache,value){var type=typeof value;cache=cache.cache;if(type=="boolean"||value==null){return cache[value]?0:-1}if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value;cache=(cache=cache[type])&&cache[key];return type=="object"?cache&&baseIndexOf(cache,value)>-1?0:-1:cache?0:-1}function cachePush(value){var cache=this.cache,type=typeof value;if(type=="boolean"||value==null){cache[value]=true}else{if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value,typeCache=cache[type]||(cache[type]={});if(type=="object"){(typeCache[key]||(typeCache[key]=[])).push(value)}else{typeCache[key]=true}}}function charAtCallback(value){return value.charCodeAt(0)}function compareAscending(a,b){var ac=a.criteria,bc=b.criteria,index=-1,length=ac.length;while(++index<length){var value=ac[index],other=bc[index];if(value!==other){if(value>other||typeof value=="undefined"){return 1}if(value<other||typeof other=="undefined"){return-1}}}return a.index-b.index}function createCache(array){var index=-1,length=array.length,first=array[0],mid=array[length/2|0],last=array[length-1];if(first&&typeof first=="object"&&mid&&typeof mid=="object"&&last&&typeof last=="object"){return false}var cache=getObject();cache["false"]=cache["null"]=cache["true"]=cache["undefined"]=false;var result=getObject();result.array=array;result.cache=cache;result.push=cachePush;while(++index<length){result.push(array[index])}return result}function escapeStringChar(match){return"\\"+stringEscapes[match]}function getArray(){return arrayPool.pop()||[]}function getObject(){return objectPool.pop()||{array:null,cache:null,criteria:null,"false":false,index:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,value:null}}function releaseArray(array){array.length=0;if(arrayPool.length<maxPoolSize){arrayPool.push(array)}}function releaseObject(object){var cache=object.cache;if(cache){releaseObject(cache)}object.array=object.cache=object.criteria=object.object=object.number=object.string=object.value=null;if(objectPool.length<maxPoolSize){objectPool.push(object)}}function slice(array,start,end){start||(start=0);if(typeof end=="undefined"){end=array?array.length:0}var index=-1,length=end-start||0,result=Array(length<0?0:length);while(++index<length){result[index]=array[start+index]}return result}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Boolean=context.Boolean,Date=context.Date,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayRef=[];var objectProto=Object.prototype;var oldDash=context._;var toString=objectProto.toString;var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,fnToString=Function.prototype.toString,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,hasOwnProperty=objectProto.hasOwnProperty,push=arrayRef.push,setTimeout=context.setTimeout,splice=arrayRef.splice,unshift=arrayRef.unshift;var defineProperty=function(){try{var o={},func=isNative(func=Object.defineProperty)&&func,result=func(o,o,o)&&func}catch(e){}return result}();var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeIsFinite=context.isFinite,nativeIsNaN=context.isNaN,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random;var ctorByClass={};ctorByClass[arrayClass]=Array;ctorByClass[boolClass]=Boolean;ctorByClass[dateClass]=Date;ctorByClass[funcClass]=Function;ctorByClass[objectClass]=Object;ctorByClass[numberClass]=Number;ctorByClass[regexpClass]=RegExp;ctorByClass[stringClass]=String;function lodash(value){return value&&typeof value=="object"&&!isArray(value)&&hasOwnProperty.call(value,"__wrapped__")?value:new lodashWrapper(value)}function lodashWrapper(value,chainAll){this.__chain__=!!chainAll;this.__wrapped__=value}lodashWrapper.prototype=lodash.prototype;var support=lodash.support={};support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";lodash.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function baseBind(bindData){var func=bindData[0],partialArgs=bindData[2],thisArg=bindData[4];function bound(){if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(this instanceof bound){var thisBinding=baseCreate(func.prototype),result=func.apply(thisBinding,args||arguments);return isObject(result)?result:thisBinding}return func.apply(thisArg,args||arguments)}setBindData(bound,bindData);return bound}function baseClone(value,isDeep,callback,stackA,stackB){if(callback){var result=callback(value);if(typeof result!="undefined"){return result}}var isObj=isObject(value);if(isObj){var className=toString.call(value);if(!cloneableClasses[className]){return value}var ctor=ctorByClass[className];switch(className){case boolClass:case dateClass:return new ctor(+value);case numberClass:case stringClass:return new ctor(value);case regexpClass:result=ctor(value.source,reFlags.exec(value));result.lastIndex=value.lastIndex;return result}}else{return value}var isArr=isArray(value);if(isDeep){var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}result=isArr?ctor(value.length):{}}else{result=isArr?slice(value):assign({},value)}if(isArr){if(hasOwnProperty.call(value,"index")){result.index=value.index}if(hasOwnProperty.call(value,"input")){result.input=value.input}}if(!isDeep){return result}stackA.push(value);stackB.push(result);(isArr?forEach:forOwn)(value,function(objValue,key){result[key]=baseClone(objValue,isDeep,callback,stackA,stackB)});if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseCreate(prototype,properties){return isObject(prototype)?nativeCreate(prototype):{}}if(!nativeCreate){baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}()}function baseCreateCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"||!("prototype"in func)){return func}var bindData=func.__bindData__;if(typeof bindData=="undefined"){if(support.funcNames){bindData=!func.name}bindData=bindData||!support.funcDecomp;if(!bindData){var source=fnToString.call(func);if(!support.funcNames){bindData=!reFuncName.test(source)}if(!bindData){bindData=reThis.test(source);setBindData(func,bindData)}}}if(bindData===false||bindData!==true&&bindData[1]&1){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 2:return function(a,b){return func.call(thisArg,a,b)};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)}}return bind(func,thisArg)}function baseCreateWrapper(bindData){var func=bindData[0],bitmask=bindData[1],partialArgs=bindData[2],partialRightArgs=bindData[3],thisArg=bindData[4],arity=bindData[5];var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,key=func;function bound(){var thisBinding=isBind?thisArg:this;if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(partialRightArgs||isCurry){args||(args=slice(arguments));if(partialRightArgs){push.apply(args,partialRightArgs)}if(isCurry&&args.length<arity){bitmask|=16&~32;return baseCreateWrapper([func,isCurryBound?bitmask:bitmask&~3,args,null,thisArg,arity])}}args||(args=arguments);if(isBindKey){func=thisBinding[key]}if(this instanceof bound){thisBinding=baseCreate(func.prototype);var result=func.apply(thisBinding,args);return isObject(result)?result:thisBinding}return func.apply(thisBinding,args)}setBindData(bound,bindData);return bound}function baseDifference(array,values){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,isLarge=length>=largeArraySize&&indexOf===baseIndexOf,result=[];if(isLarge){var cache=createCache(values);if(cache){indexOf=cacheIndexOf;values=cache}else{isLarge=false}}while(++index<length){var value=array[index];if(indexOf(values,value)<0){result.push(value)}}if(isLarge){releaseObject(values)}return result}function baseFlatten(array,isShallow,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value&&typeof value=="object"&&typeof value.length=="number"&&(isArray(value)||isArguments(value))){if(!isShallow){value=baseFlatten(value,isShallow,isStrict)}var valIndex=-1,valLength=value.length,resIndex=result.length;result.length+=valLength;while(++valIndex<valLength){result[resIndex++]=value[valIndex]}}else if(!isStrict){result.push(value)}}return result}function baseIsEqual(a,b,callback,isWhere,stackA,stackB){if(callback){var result=callback(a,b);if(typeof result!="undefined"){return!!result}}if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&!(a&&objectTypes[type])&&!(b&&objectTypes[otherType])){return false}if(a==null||b==null){return a===b}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:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){var aWrapped=hasOwnProperty.call(a,"__wrapped__"),bWrapped=hasOwnProperty.call(b,"__wrapped__");if(aWrapped||bWrapped){return baseIsEqual(aWrapped?a.__wrapped__:a,bWrapped?b.__wrapped__:b,callback,isWhere,stackA,stackB)}if(className!=objectClass){return false}var ctorA=a.constructor,ctorB=b.constructor;if(ctorA!=ctorB&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result||isWhere){while(size--){var index=length,value=b[size];if(isWhere){while(index--){if(result=baseIsEqual(a[index],value,callback,isWhere,stackA,stackB)){break}}}else if(!(result=baseIsEqual(a[size],value,callback,isWhere,stackA,stackB))){break}}}}else{forIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&baseIsEqual(a[key],value,callback,isWhere,stackA,stackB)}});if(result&&!isWhere){forIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseMerge(object,source,callback,stackA,stackB){(isArray(source)?forEach:forOwn)(source,function(source,key){var found,isArr,result=source,value=object[key];if(source&&((isArr=isArray(source))||isPlainObject(source))){var stackLength=stackA.length;while(stackLength--){if(found=stackA[stackLength]==source){value=stackB[stackLength];break}}if(!found){var isShallow;if(callback){result=callback(value,source);if(isShallow=typeof result!="undefined"){value=result}}if(!isShallow){value=isArr?isArray(value)?value:[]:isPlainObject(value)?value:{}}stackA.push(source);stackB.push(value);if(!isShallow){baseMerge(value,source,callback,stackA,stackB)}}}else{if(callback){result=callback(value,source);if(typeof result=="undefined"){result=source}}if(typeof result!="undefined"){value=result}}object[key]=value})}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseUniq(array,isSorted,callback){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,result=[];var isLarge=!isSorted&&length>=largeArraySize&&indexOf===baseIndexOf,seen=callback||isLarge?getArray():result;if(isLarge){var cache=createCache(seen);indexOf=cacheIndexOf;seen=cache}while(++index<length){var value=array[index],computed=callback?callback(value,index,array):value;if(isSorted?!index||seen[seen.length-1]!==computed:indexOf(seen,computed)<0){if(callback||isLarge){seen.push(computed)}result.push(value)}}if(isLarge){releaseArray(seen.array);releaseObject(seen)}else if(callback){releaseArray(seen)}return result}function createAggregator(setter){return function(collection,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];setter(result,value,callback(value,index,collection),collection)}}else{forOwn(collection,function(value,key,collection){setter(result,value,callback(value,key,collection),collection)})}return result}}function createWrapper(func,bitmask,partialArgs,partialRightArgs,thisArg,arity){var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,isPartial=bitmask&16,isPartialRight=bitmask&32;if(!isBindKey&&!isFunction(func)){throw new TypeError}if(isPartial&&!partialArgs.length){bitmask&=~16;isPartial=partialArgs=false}if(isPartialRight&&!partialRightArgs.length){bitmask&=~32;isPartialRight=partialRightArgs=false}var bindData=func&&func.__bindData__;if(bindData&&bindData!==true){bindData=slice(bindData);if(bindData[2]){bindData[2]=slice(bindData[2])}if(bindData[3]){bindData[3]=slice(bindData[3])}if(isBind&&!(bindData[1]&1)){bindData[4]=thisArg}if(!isBind&&bindData[1]&1){bitmask|=8}if(isCurry&&!(bindData[1]&4)){bindData[5]=arity}if(isPartial){push.apply(bindData[2]||(bindData[2]=[]),partialArgs)}if(isPartialRight){unshift.apply(bindData[3]||(bindData[3]=[]),partialRightArgs)}bindData[1]|=bitmask;return createWrapper.apply(null,bindData)}var creater=bitmask==1||bitmask===17?baseBind:baseCreateWrapper;return creater([func,bitmask,partialArgs,partialRightArgs,thisArg,arity])}function escapeHtmlChar(match){return htmlEscapes[match]}function getIndexOf(){var result=(result=lodash.indexOf)===indexOf?baseIndexOf:result;return result}function isNative(value){return typeof value=="function"&&reNative.test(value)}var setBindData=!defineProperty?noop:function(func,value){descriptor.value=value;defineProperty(func,"__bindData__",descriptor)};function shimIsPlainObject(value){var ctor,result;if(!(value&&toString.call(value)==objectClass)||(ctor=value.constructor,isFunction(ctor)&&!(ctor instanceof ctor))){return false}forIn(value,function(value,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function unescapeHtmlChar(match){return htmlUnescapes[match]}function isArguments(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==argsClass||false}var isArray=nativeIsArray||function(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==arrayClass||false};var shimKeys=function(object){var index,iterable=object,result=[];if(!iterable)return result;if(!objectTypes[typeof object])return result;for(index in iterable){if(hasOwnProperty.call(iterable,index)){result.push(index)}}return result};var keys=!nativeKeys?shimKeys:function(object){if(!isObject(object)){return[]}return nativeKeys(object)};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var htmlUnescapes=invert(htmlEscapes);var reEscapedHtml=RegExp("("+keys(htmlUnescapes).join("|")+")","g"),reUnescapedHtml=RegExp("["+keys(htmlEscapes).join("")+"]","g");var assign=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;if(argsLength>3&&typeof args[argsLength-2]=="function"){var callback=baseCreateCallback(args[--argsLength-1],args[argsLength--],2)}else if(argsLength>2&&typeof args[argsLength-1]=="function"){callback=args[--argsLength]}while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];result[index]=callback?callback(result[index],iterable[index]):iterable[index]}}}return result};function clone(value,isDeep,callback,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=callback;callback=isDeep;isDeep=false}return baseClone(value,isDeep,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function cloneDeep(value,callback,thisArg){return baseClone(value,true,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function create(prototype,properties){var result=baseCreate(prototype);return properties?assign(result,properties):result}var defaults=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(typeof result[index]=="undefined")result[index]=iterable[index]}}}return result};function findKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}function findLastKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwnRight(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}var forIn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);for(index in iterable){if(callback(iterable[index],index,collection)===false)return result}return result};function forInRight(object,callback,thisArg){var pairs=[];forIn(object,function(value,key){pairs.push(key,value)});var length=pairs.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){if(callback(pairs[length--],pairs[length],object)===false){break}}return object}var forOwn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(callback(iterable[index],index,collection)===false)return result}return result};function forOwnRight(object,callback,thisArg){var props=keys(object),length=props.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){var key=props[length];if(callback(object[key],key,object)===false){break}}return object}function functions(object){var result=[];forIn(object,function(value,key){if(isFunction(value)){result.push(key)}});return result.sort()}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object){var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index];result[object[key]]=key}return result}function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)==boolClass||false}function isDate(value){return value&&typeof value=="object"&&toString.call(value)==dateClass||false}function isElement(value){return value&&value.nodeType===1||false}function isEmpty(value){var result=true;if(!value){return result}var className=toString.call(value),length=value.length;if(className==arrayClass||className==stringClass||className==argsClass||className==objectClass&&typeof length=="number"&&isFunction(value.splice)){return!length}forOwn(value,function(){return result=false});return result}function isEqual(a,b,callback,thisArg){return baseIsEqual(a,b,typeof callback=="function"&&baseCreateCallback(callback,thisArg,2))}function isFinite(value){return nativeIsFinite(value)&&!nativeIsNaN(parseFloat(value))}function isFunction(value){return typeof value=="function"}function isObject(value){return!!(value&&objectTypes[typeof value])}function isNaN(value){return isNumber(value)&&value!=+value}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||value&&typeof value=="object"&&toString.call(value)==numberClass||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&toString.call(value)==objectClass)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return value&&typeof value=="object"&&toString.call(value)==regexpClass||false}function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)==stringClass||false}function isUndefined(value){return typeof value=="undefined"}function mapValues(object,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){result[key]=callback(value,key,object)});return result}function merge(object){var args=arguments,length=2;if(!isObject(object)){return object}if(typeof args[2]!="number"){length=args.length}if(length>3&&typeof args[length-2]=="function"){var callback=baseCreateCallback(args[--length-1],args[length--],2)}else if(length>2&&typeof args[length-1]=="function"){callback=args[--length]}var sources=slice(arguments,1,length),index=-1,stackA=getArray(),stackB=getArray();while(++index<length){baseMerge(object,sources[index],callback,stackA,stackB)}releaseArray(stackA);releaseArray(stackB);return object}function omit(object,callback,thisArg){var result={};if(typeof callback!="function"){var props=[];forIn(object,function(value,key){props.push(key)});props=baseDifference(props,baseFlatten(arguments,true,false,1));var index=-1,length=props.length;while(++index<length){var key=props[index];result[key]=object[key]}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(!callback(value,key,object)){result[key]=value}})}return result}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,callback,thisArg){var result={};if(typeof callback!="function"){var index=-1,props=baseFlatten(arguments,true,false,1),length=isObject(object)?props.length:0;while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(callback(value,key,object)){result[key]=value}})}return result}function transform(object,callback,accumulator,thisArg){var isArr=isArray(object);if(accumulator==null){if(isArr){accumulator=[]}else{var ctor=object&&object.constructor,proto=ctor&&ctor.prototype;accumulator=baseCreate(proto)}}if(callback){callback=lodash.createCallback(callback,thisArg,4);(isArr?forEach:forOwn)(object,function(value,index,object){return callback(accumulator,value,index,object)})}return accumulator}function values(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function at(collection){var args=arguments,index=-1,props=baseFlatten(args,true,false,1),length=args[2]&&args[2][args[1]]===collection?1:props.length,result=Array(length);while(++index<length){result[index]=collection[props[index]]}return result}function contains(collection,target,fromIndex){var index=-1,indexOf=getIndexOf(),length=collection?collection.length:0,result=false;fromIndex=(fromIndex<0?nativeMax(0,length+fromIndex):fromIndex)||0;if(isArray(collection)){result=indexOf(collection,target,fromIndex)>-1}else if(typeof length=="number"){result=(isString(collection)?collection.indexOf(target,fromIndex):indexOf(collection,target,fromIndex))>-1}else{forOwn(collection,function(value){if(++index>=fromIndex){return!(result=value===target)}})}return result}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key]++:result[key]=1});function every(collection,callback,thisArg){var result=true;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(!(result=!!callback(collection[index],index,collection))){break}}}else{forOwn(collection,function(value,index,collection){return result=!!callback(value,index,collection)})}return result}function filter(collection,callback,thisArg){var result=[];callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){result.push(value)}}}else{forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result.push(value)}})}return result}function find(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){return value}}}else{var result;forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}}function findLast(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forEachRight(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}function forEach(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(++index<length){if(callback(collection[index],index,collection)===false){break}}}else{forOwn(collection,callback)}return collection}function forEachRight(collection,callback,thisArg){var length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(length--){if(callback(collection[length],length,collection)===false){break}}}else{var props=keys(collection);length=props.length;forOwn(collection,function(value,key,collection){key=props?props[--length]:--length;return callback(collection[key],key,collection)})}return collection}var groupBy=createAggregator(function(result,value,key){(hasOwnProperty.call(result,key)?result[key]:result[key]=[]).push(value)});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){var args=slice(arguments,2),index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){result[++index]=(isFunc?methodName:value[methodName]).apply(value,args)});return result}function map(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=lodash.createCallback(callback,thisArg,3);if(typeof length=="number"){var result=Array(length);while(++index<length){result[index]=callback(collection[index],index,collection)}}else{result=[];forOwn(collection,function(value,key,collection){result[++index]=callback(value,key,collection)})}return result}function max(collection,callback,thisArg){var computed=-Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value>result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current>computed){computed=current;result=value}})}return result}function min(collection,callback,thisArg){var computed=Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value<result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current<computed){computed=current;result=value}})}return result}var pluck=map;function reduce(collection,callback,accumulator,thisArg){if(!collection)return accumulator;var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);var index=-1,length=collection.length;if(typeof length=="number"){if(noaccum){accumulator=collection[++index]}while(++index<length){accumulator=callback(accumulator,collection[index],index,collection)}}else{forOwn(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)})}return accumulator}function reduceRight(collection,callback,accumulator,thisArg){var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);forEachRight(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)});return accumulator}function reject(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);return filter(collection,function(value,index,collection){return!callback(value,index,collection)})}function sample(collection,n,guard){if(collection&&typeof collection.length!="number"){collection=values(collection)}if(n==null||guard){return collection?collection[baseRandom(0,collection.length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(nativeMax(0,n),result.length);return result}function shuffle(collection){var index=-1,length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){var rand=baseRandom(0,++index);result[index]=result[rand];result[rand]=value});return result}function size(collection){var length=collection?collection.length:0;return typeof length=="number"?length:keys(collection).length}function some(collection,callback,thisArg){var result; callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(result=callback(collection[index],index,collection)){break}}}else{forOwn(collection,function(value,index,collection){return!(result=callback(value,index,collection))})}return!!result}function sortBy(collection,callback,thisArg){var index=-1,isArr=isArray(callback),length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);if(!isArr){callback=lodash.createCallback(callback,thisArg,3)}forEach(collection,function(value,key,collection){var object=result[++index]=getObject();if(isArr){object.criteria=map(callback,function(key){return value[key]})}else{(object.criteria=getArray())[0]=callback(value,key,collection)}object.index=index;object.value=value});length=result.length;result.sort(compareAscending);while(length--){var object=result[length];result[length]=object.value;if(!isArr){releaseArray(object.criteria)}releaseObject(object)}return result}function toArray(collection){if(collection&&typeof collection.length=="number"){return slice(collection)}return values(collection)}var where=filter;function compact(array){var index=-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value){result.push(value)}}return result}function difference(array){return baseDifference(array,baseFlatten(arguments,true,true,1))}function findIndex(array,callback,thisArg){var index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length){if(callback(array[index],index,array)){return index}}return-1}function findLastIndex(array,callback,thisArg){var length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(length--){if(callback(array[length],length,array)){return length}}return-1}function first(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=-1;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[0]:undefined}}return slice(array,0,nativeMin(nativeMax(0,n),length))}function flatten(array,isShallow,callback,thisArg){if(typeof isShallow!="boolean"&&isShallow!=null){thisArg=callback;callback=typeof isShallow!="function"&&thisArg&&thisArg[isShallow]===array?null:isShallow;isShallow=false}if(callback!=null){array=map(array,callback,thisArg)}return baseFlatten(array,isShallow)}function indexOf(array,value,fromIndex){if(typeof fromIndex=="number"){var length=array?array.length:0;fromIndex=fromIndex<0?nativeMax(0,length+fromIndex):fromIndex||0}else if(fromIndex){var index=sortedIndex(array,value);return array[index]===value?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:callback||n}return slice(array,0,nativeMin(nativeMax(0,length-n),length))}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=getArray(),indexOf=getIndexOf(),trustIndexOf=indexOf===baseIndexOf,seen=getArray();while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(trustIndexOf&&value.length>=largeArraySize&&createCache(argsIndex?args[argsIndex]:seen))}}var array=args[0],index=-1,length=array?array.length:0,result=[];outer:while(++index<length){var cache=caches[0];value=array[index];if((cache?cacheIndexOf(cache,value):indexOf(seen,value))<0){argsIndex=argsLength;(cache||seen).push(value);while(--argsIndex){cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}result.push(value)}}while(argsLength--){cache=caches[argsLength];if(cache){releaseObject(cache)}}releaseArray(caches);releaseArray(seen);return result}function last(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[length-1]:undefined}}return slice(array,nativeMax(0,length-n))}function lastIndexOf(array,value,fromIndex){var index=array?array.length:0;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(0,index+fromIndex):nativeMin(fromIndex,index-1))+1}while(index--){if(array[index]===value){return index}}return-1}function pull(array){var args=arguments,argsIndex=0,argsLength=args.length,length=array?array.length:0;while(++argsIndex<argsLength){var index=-1,value=args[argsIndex];while(++index<length){if(array[index]===value){splice.call(array,index--,1);length--}}}return array}function range(start,end,step){start=+start||0;step=typeof step=="number"?step:+step||1;if(end==null){end=start;start=0}var index=-1,length=nativeMax(0,ceil((end-start)/(step||1))),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function remove(array,callback,thisArg){var index=-1,length=array?array.length:0,result=[];callback=lodash.createCallback(callback,thisArg,3);while(++index<length){var value=array[index];if(callback(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array,callback,thisArg){if(typeof callback!="number"&&callback!=null){var n=0,index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:nativeMax(0,callback)}return slice(array,n)}function sortedIndex(array,value,callback,thisArg){var low=0,high=array?array.length:low;callback=callback?lodash.createCallback(callback,thisArg,1):identity;value=callback(value);while(low<high){var mid=low+high>>>1;callback(array[mid])<value?low=mid+1:high=mid}return low}function union(){return baseUniq(baseFlatten(arguments,true,true))}function uniq(array,isSorted,callback,thisArg){if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=callback;callback=typeof isSorted!="function"&&thisArg&&thisArg[isSorted]===array?null:isSorted;isSorted=false}if(callback!=null){callback=lodash.createCallback(callback,thisArg,3)}return baseUniq(array,isSorted,callback)}function without(array){return baseDifference(array,slice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseUniq(baseDifference(result,array).concat(baseDifference(array,result))):array}}return result||[]}function zip(){var array=arguments.length>1?arguments:arguments[0],index=-1,length=array?max(pluck(array,"length")):0,result=Array(length<0?0:length);while(++index<length){result[index]=pluck(array,index)}return result}function zipObject(keys,values){var index=-1,length=keys?keys.length:0,result={};if(!values&&length&&!isArray(keys[0])){values=[]}while(++index<length){var key=keys[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function after(n,func){if(!isFunction(func)){throw new TypeError}return function(){if(--n<1){return func.apply(this,arguments)}}}function bind(func,thisArg){return arguments.length>2?createWrapper(func,17,slice(arguments,2),null,thisArg):createWrapper(func,1,null,null,thisArg)}function bindAll(object){var funcs=arguments.length>1?baseFlatten(arguments,true,false,1):functions(object),index=-1,length=funcs.length;while(++index<length){var key=funcs[index];object[key]=createWrapper(object[key],1,null,null,object)}return object}function bindKey(object,key){return arguments.length>2?createWrapper(key,19,slice(arguments,2),null,object):createWrapper(key,3,null,null,object)}function compose(){var funcs=arguments,length=funcs.length;while(length--){if(!isFunction(funcs[length])){throw new TypeError}}return function(){var args=arguments,length=funcs.length;while(length--){args=[funcs[length].apply(this,args)]}return args[0]}}function curry(func,arity){arity=typeof arity=="number"?arity:+arity||func.length;return createWrapper(func,4,null,null,null,arity)}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError}wait=nativeMax(0,wait)||0;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&(nativeMax(wait,options.maxWait)||0);trailing="trailing"in options?options.trailing:trailing}var delayed=function(){var remaining=wait-(now()-stamp);if(remaining<=0){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}};var maxDelayed=function(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}};return function(){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;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=null}return result}}function defer(func){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,1);return setTimeout(function(){func.apply(undefined,args)},1)}function delay(func,wait){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,2);return setTimeout(function(){func.apply(undefined,args)},wait)}function memoize(func,resolver){if(!isFunction(func)){throw new TypeError}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):keyPrefix+arguments[0];return hasOwnProperty.call(cache,key)?cache[key]:cache[key]=func.apply(this,arguments)};memoized.cache={};return memoized}function once(func){var ran,result;if(!isFunction(func)){throw new TypeError}return function(){if(ran){return result}ran=true;result=func.apply(this,arguments);func=null;return result}}function partial(func){return createWrapper(func,16,slice(arguments,1))}function partialRight(func){return createWrapper(func,32,null,slice(arguments,1))}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?options.leading:leading;trailing="trailing"in options?options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){return createWrapper(wrapper,16,[value])}function constant(value){return function(){return value}}function createCallback(func,thisArg,argCount){var type=typeof func;if(func==null||type=="function"){return baseCreateCallback(func,thisArg,argCount)}if(type!="object"){return property(func)}var props=keys(func),key=props[0],a=func[key];if(props.length==1&&a===a&&!isObject(a)){return function(object){var b=object[key];return a===b&&(a!==0||1/a==1/b)}}return function(object){var length=props.length,result=false;while(length--){if(!(result=baseIsEqual(object[props[length]],func[props[length]],null,true))){break}}return result}}function escape(string){return string==null?"":String(string).replace(reUnescapedHtml,escapeHtmlChar)}function identity(value){return value}function mixin(object,source,options){var chain=true,methodNames=source&&functions(source);if(!source||!options&&!methodNames.length){if(options==null){options=source}ctor=lodashWrapper;source=object;object=lodash;methodNames=functions(source)}if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}var ctor=object,isFunc=isFunction(ctor);forEach(methodNames,function(methodName){var func=object[methodName]=source[methodName];if(isFunc){ctor.prototype[methodName]=function(){var chainAll=this.__chain__,value=this.__wrapped__,args=[value];push.apply(args,arguments);var result=func.apply(object,args);if(chain||chainAll){if(value===result&&isObject(result)){return this}result=new ctor(result);result.__chain__=chainAll}return result}}})}function noConflict(){context._=oldDash;return this}function noop(){}var now=isNative(now=Date.now)&&now||function(){return(new Date).getTime()};var parseInt=nativeParseInt(whitespace+"08")==8?nativeParseInt:function(value,radix){return nativeParseInt(isString(value)?value.replace(reLeadingSpacesAndZeros,""):value,radix||0)};function property(key){return function(object){return object[key]}}function random(min,max,floating){var noMin=min==null,noMax=max==null;if(floating==null){if(typeof min=="boolean"&&noMax){floating=min;min=1}else if(!noMax&&typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}function result(object,key){if(object){var value=object[key];return isFunction(value)?object[key]():value}}function template(text,data,options){var settings=lodash.templateSettings;text=String(text||"");options=defaults({},options,settings);var imports=defaults({},options.imports,settings.imports),importsKeys=keys(imports),importsValues=values(imports);var isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");text.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=text.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable,hasVariable=variable;if(!hasVariable){variable="obj";source="with ("+variable+") {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+variable+") {\n"+(hasVariable?"":variable+" || ("+variable+" = {});\n")+"var __t, __p = '', __e = _.escape"+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var sourceURL="\n/*\n//# sourceURL="+(options.sourceURL||"/lodash/template/source["+templateCounter++ +"]")+"\n*/";try{var result=Function(importsKeys,"return "+source+sourceURL).apply(undefined,importsValues)}catch(e){e.source=source;throw e}if(data){return result(data)}result.source=source;return result}function times(n,callback,thisArg){n=(n=+n)>-1?n:0;var index=-1,result=Array(n);callback=baseCreateCallback(callback,thisArg,1);while(++index<n){result[index]=callback(index)}return result}function unescape(string){return string==null?"":String(string).replace(reEscapedHtml,unescapeHtmlChar)}function uniqueId(prefix){var id=++idCounter;return String(prefix==null?"":prefix)+id}function chain(value){value=new lodashWrapper(value);value.__chain__=true;return value}function tap(value,interceptor){interceptor(value);return value}function wrapperChain(){this.__chain__=true;return this}function wrapperToString(){return String(this.__wrapped__)}function wrapperValueOf(){return this.__wrapped__}lodash.after=after;lodash.assign=assign;lodash.at=at;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.compact=compact;lodash.compose=compose;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.createCallback=createCallback;lodash.curry=curry;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.filter=filter;lodash.flatten=flatten;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.map=map;lodash.mapValues=mapValues;lodash.max=max;lodash.memoize=memoize;lodash.merge=merge;lodash.min=min;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.pull=pull;lodash.range=range;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.sortBy=sortBy;lodash.tap=tap;lodash.throttle=throttle;lodash.times=times;lodash.toArray=toArray;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.values=values;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.collect=map;lodash.drop=rest;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;lodash.unzip=zip;mixin(lodash);lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.contains=contains;lodash.escape=escape;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.has=has;lodash.identity=identity;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isNaN=isNaN;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isUndefined=isUndefined;lodash.lastIndexOf=lastIndexOf;lodash.mixin=mixin;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.template=template;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.all=every;lodash.any=some;lodash.detect=find;lodash.findWhere=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.include=contains;lodash.inject=reduce;mixin(function(){var source={};forOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.first=first;lodash.last=last;lodash.sample=sample;lodash.take=first;lodash.head=first;forOwn(lodash,function(func,methodName){var callbackable=methodName!=="sample";if(!lodash.prototype[methodName]){lodash.prototype[methodName]=function(n,guard){var chainAll=this.__chain__,result=func(this.__wrapped__,n,guard);return!chainAll&&(n==null||guard&&!(callbackable&&typeof n=="function"))?result:new lodashWrapper(result,chainAll)}}});lodash.VERSION="2.4.1";lodash.prototype.chain=wrapperChain;lodash.prototype.toString=wrapperToString;lodash.prototype.value=wrapperValueOf;lodash.prototype.valueOf=wrapperValueOf;forEach(["join","pop","shift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){var chainAll=this.__chain__,result=func.apply(this.__wrapped__,arguments);return chainAll?new lodashWrapper(result,chainAll):result}});forEach(["push","reverse","sort","unshift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){func.apply(this.__wrapped__,arguments);return this}});forEach(["concat","slice","splice"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){return new lodashWrapper(func.apply(this.__wrapped__,arguments),this.__chain__)}});return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],105:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],106:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:108}],107:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],108:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end) }index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<=65535&&end<=65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}else{loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,end+1)}}else if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}else if(start<HIGH_SURROGATE_MIN&&end>HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,end+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,end+1)}}else if(start<=65535&&end>65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,65535+1)}else if(start<HIGH_SURROGATE_MIN){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,65535+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,65535+1)}astral.push(65535+1,end+1)}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneSurrogates=!dataIsEmpty(loneHighSurrogates);var surrogateMappings=surrogateSet(astral);if(!hasAstral&&hasLoneSurrogates){bmp=dataAddData(bmp,loneHighSurrogates)}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasAstral&&hasLoneSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.0.1";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(){var result=createCharacterClassesFromData(this.data);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],109:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],110:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,6})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],111:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString()); break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":106,"./data/iu-mappings.json":107,regenerate:108,regjsgen:109,regjsparser:110}],112:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":117,"./source-map/source-map-generator":118,"./source-map/source-node":119}],113:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":120,amdefine:121}],114:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":115,amdefine:121}],115:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:121}],116:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return aHaystack[mid]}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return aHaystack[mid]}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?null:aHaystack[aLow]}}exports.search=function search(aNeedle,aHaystack,aCompare){return aHaystack.length>0?recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare):null}})},{amdefine:121}],117:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);smc.__originalMappings=aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var mapping=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(mapping&&mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mapping=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(mapping){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null)}}return{line:null,column:null}};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":113,"./base64-vlq":114,"./binary-search":116,"./util":120,amdefine:121}],118:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=[];this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);this._validateMapping(generated,original,source,name);if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.push({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.forEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;this._mappings.sort(util.compareByGeneratedPositions);for(var i=0,len=this._mappings.length;i<len;i++){mapping=this._mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":113,"./base64-vlq":114,"./util":120,amdefine:121}],119:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var REGEX_CHARACTER=/\r\n|[\s\S]/g;function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk instanceof SourceNode){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild instanceof SourceNode){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i]instanceof SourceNode){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}chunk.match(REGEX_CHARACTER).forEach(function(ch,idx,array){if(REGEX_NEWLINE.test(ch)){generated.line++;generated.column=0;if(idx+1===array.length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column+=ch.length}})});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":118,"./util":120,amdefine:121}],120:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:121}],121:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps) })}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:96,path:95}],122:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-delete":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceDelete"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-get":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-set":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceSet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"VALUE"}]}}]},"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}}]},"arguments-to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"NewExpression",callee:{type:"Identifier",name:"Array"},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"length"},computed:false}]}}],kind:"var"},{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:{type:"Literal",value:0}}],kind:"var"},test:{type:"BinaryExpression",left:{type:"Identifier",name:"i"},operator:"<",right:{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"length"},computed:false}},update:{type:"UpdateExpression",operator:"++",prefix:false,argument:{type:"Identifier",name:"i"}},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-expression-comprehension-filter":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"filter"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"FILTER"}}]},expression:false}]},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-expression-comprehension-map":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}]},"class-props":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}}]},"class-super-constructor-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},"class":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"CLASS_NAME"},init:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"CLASS_NAME"}}]},expression:false}},arguments:[]}}]},"exports-assign-key":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"VARIABLE_NAME"},computed:false},right:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"KEY"},computed:false}}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"default"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"parent"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"parent"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"child"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"parent"}}}]},expression:false}}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"ParenthesizedExpression",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"if-undefined-set-to":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"VARIABLE"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"VARIABLE"},right:{type:"Identifier",name:"DEFAULT"}}},alternate:null}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}}]},expression:false}}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"Identifier",name:"CONTENT"}},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"object-define-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"PROPS"}]}}]},"object-spread":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},"require-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],kind:"var"}]},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}]},"self-global":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"self"},alternate:{type:"Identifier",name:"global"}}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"raw"},kind:"init"}]},kind:"init"}]}]}}]},expression:false}}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"exports"},{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}]},alternate:null}}]},expression:false}}}]}}},{}]},{},[2])(2)});
MyWeibo/node_modules/react/lib/ReactNodeTypes.js
alucardlockon/LearnCode
/** * Copyright 2013-present, 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. * * @providesModule ReactNodeTypes * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactElement = require('./ReactElement'); var invariant = require('fbjs/lib/invariant'); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (ReactElement.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } !false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes;
client/src/Components/FacetContainer/FacetContainer.js
CrashsLanding/petfinder-searcher
import React from 'react'; import './FacetContainer.css'; import Facet from '../Facet/Facet'; import _ from 'lodash'; class FacetContainer extends React.Component { constructor(props) { super(props); this.state = { facets: {} }; } toggleAndFacet(facetName, e) { let the_state = _.clone(this.props); if (_.includes(the_state.andFacets, facetName)) { the_state.andFacets = _.remove(the_state.andFacets, facetName); } else { the_state.andFacets.push(facetName); } this.props.onAndFacetChange(the_state.andFacets); } toggleFacetEntry(facetName, facetEntryValue, e) { let the_state = _.clone(this.props); let selected = the_state.facets[facetName][facetEntryValue]; the_state.facets[facetName][facetEntryValue] = !selected; let selectedFacets = _.reduce(_.map(the_state.facets, (facetEntry, facetName) => { let selectedFacet = {}; selectedFacet[facetName] = _.compact(_.map(facetEntry, (facetEntryValue, facetEntryKey) => { if (facetEntryValue) return facetEntryKey; })); return selectedFacet; }), (result, value) => _.merge(result, value), {}); the_state.selectedFacets = selectedFacets; this.props.onFacetChange(the_state.selectedFacets); } render() { return <div className="FacetContainer col-xs-12 col-sm-3"> {_.map(_.keys(this.props.facets), (facetKey, index) => { let toggleFunction = _.partial(this.toggleFacetEntry, facetKey); let andFunction = _.partial(this.toggleAndFacet, facetKey); return <Facet key={index} name={facetKey} values={this.props.facets[facetKey]} andFunction={andFunction.bind(this)} andFacets={this.props.andFacets} andAbleFacets={this.props.andAbleFacets} toggleFunction={toggleFunction.bind(this)}> </Facet>; })} </div> } } FacetContainer.propTypes = { facets: React.PropTypes.object, onFacetChange: React.PropTypes.func } export default FacetContainer;
src/containers/DevTools/DevTools.js
mozilla/mozlando-frontend-demo
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-shift-h" defaultIsVisible={false} changePositionKey="Q"> <LogMonitor /> </DockMonitor> );
ajax/libs/react-select/1.0.0-rc.3/react-select.min.js
Amomo/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Select=e()}}(function(){return function e(t,u,n){function s(i,a){if(!u[i]){if(!t[i]){var r="function"==typeof require&&require;if(!a&&r)return r(i,!0);if(o)return o(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var p=u[i]={exports:{}};t[i][0].call(p.exports,function(e){var u=t[i][1][e];return s(u?u:e)},p,p.exports,e,t,u,n)}return u[i].exports}for(var o="function"==typeof require&&require,i=0;i<n.length;i++)s(n[i]);return s}({1:[function(e,t,u){(function(n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,u){return t in e?Object.defineProperty(e,t,{value:u,enumerable:!0,configurable:!0,writable:!0}):e[t]=u,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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 r(e){return f["default"].createElement(E["default"],e)}Object.defineProperty(u,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var u=arguments[t];for(var n in u)Object.prototype.hasOwnProperty.call(u,n)&&(e[n]=u[n])}return e},p=function(){function e(e,t){for(var u=0;u<t.length;u++){var n=t[u];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,u,n){return u&&e(t.prototype,u),n&&e(t,n),t}}(),d=function(e,t,u){for(var n=!0;n;){var s=e,o=t,i=u;n=!1,null===s&&(s=Function.prototype);var a=Object.getOwnPropertyDescriptor(s,o);if(void 0!==a){if("value"in a)return a.value;var r=a.get;if(void 0===r)return;return r.call(i)}var l=Object.getPrototypeOf(s);if(null===l)return;e=l,t=o,u=i,n=!0,a=l=void 0}},c="undefined"!=typeof window?window.React:"undefined"!=typeof n?n.React:null,f=s(c),h=e("./Select"),E=s(h),y=e("./utils/stripDiacritics"),g=s(y),b={autoload:f["default"].PropTypes.bool.isRequired,cache:f["default"].PropTypes.any,children:f["default"].PropTypes.func.isRequired,ignoreAccents:f["default"].PropTypes.bool,ignoreCase:f["default"].PropTypes.bool,loadingPlaceholder:f["default"].PropTypes.oneOfType([f["default"].PropTypes.string,f["default"].PropTypes.node]),loadOptions:f["default"].PropTypes.func.isRequired,options:c.PropTypes.array.isRequired,placeholder:f["default"].PropTypes.oneOfType([f["default"].PropTypes.string,f["default"].PropTypes.node]),noResultsText:f["default"].PropTypes.oneOfType([f["default"].PropTypes.string,f["default"].PropTypes.node]),onChange:f["default"].PropTypes.func,searchPromptText:f["default"].PropTypes.oneOfType([f["default"].PropTypes.string,f["default"].PropTypes.node]),onInputChange:f["default"].PropTypes.func,value:f["default"].PropTypes.any},v={},m={autoload:!0,cache:v,children:r,ignoreAccents:!0,ignoreCase:!0,loadingPlaceholder:"Loading...",options:[],searchPromptText:"Type to search"},C=function(e){function t(e,u){i(this,t),d(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e,u),this._cache=e.cache===v?{}:e.cache,this.state={isLoading:!1,options:e.options},this._onInputChange=this._onInputChange.bind(this)}return a(t,e),p(t,[{key:"componentDidMount",value:function(){var e=this.props.autoload;e&&this.loadOptions("")}},{key:"componentWillUpdate",value:function(e,t){var u=this,n=["options"];n.forEach(function(t){u.props[t]!==e[t]&&u.setState(o({},t,e[t]))})}},{key:"clearOptions",value:function(){this.setState({options:[]})}},{key:"loadOptions",value:function u(e){var t=this,u=this.props.loadOptions,n=this._cache;if(n&&n.hasOwnProperty(e))return void this.setState({options:n[e]});var s=function i(u,s){if(i===t._callback){t._callback=null;var o=s&&s.options||[];n&&(n[e]=o),t.setState({isLoading:!1,options:o})}};this._callback=s;var o=u(e,s);return o&&o.then(function(e){return s(null,e)},function(e){return s(e)}),this._callback&&!this.state.isLoading&&this.setState({isLoading:!0}),e}},{key:"_onInputChange",value:function(e){var t=this.props,u=t.ignoreAccents,n=t.ignoreCase,s=t.onInputChange;return u&&(e=(0,g["default"])(e)),n&&(e=e.toLowerCase()),s&&s(e),this.loadOptions(e)}},{key:"inputValue",value:function(){return this.select?this.select.state.inputValue:""}},{key:"noResultsText",value:function n(){var e=this.props,t=e.loadingPlaceholder,n=e.noResultsText,u=e.searchPromptText,s=this.state.isLoading,o=this.inputValue();return s?t:o&&n?n:u}},{key:"focus",value:function(){this.select.focus()}},{key:"render",value:function(){var e=this,t=this.props,u=t.children,n=t.loadingPlaceholder,s=t.placeholder,o=this.state,i=o.isLoading,a=o.options,r={noResultsText:this.noResultsText(),placeholder:i?n:s,options:i&&n?[]:a,ref:function(t){return e.select=t},onChange:function(t){e.props.multi&&e.props.value&&t.length>e.props.value.length&&e.clearOptions(),e.props.onChange(t)}};return u(l({},this.props,r,{isLoading:i,onInputChange:this._onInputChange}))}}]),t}(c.Component);u["default"]=C,C.propTypes=b,C.defaultProps=m,t.exports=u["default"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Select":5,"./utils/stripDiacritics":11}],2:[function(e,t,u){(function(u){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function s(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return Object.keys(e).reduce(function(t,u){var n=e[u];return void 0!==n&&(t[u]=n),t},t)}var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var u=arguments[t];for(var n in u)Object.prototype.hasOwnProperty.call(u,n)&&(e[n]=u[n])}return e},i="undefined"!=typeof window?window.React:"undefined"!=typeof u?u.React:null,a=n(i),r=e("./Select"),l=n(r),p=a["default"].createClass({displayName:"AsyncCreatableSelect",render:function(){var e=this;return a["default"].createElement(l["default"].Async,this.props,function(t){return a["default"].createElement(l["default"].Creatable,e.props,function(e){return a["default"].createElement(l["default"],o({},s(t,s(e,{})),{onInputChange:function(u){return e.onInputChange(u),t.onInputChange(u)},ref:function(u){e.ref(u),t.ref(u)}}))})})}});t.exports=p}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Select":5}],3:[function(e,t,u){(function(u){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function s(e,t){var u={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(u[n]=e[n]);return u}function o(e){return f["default"].createElement(E["default"],e)}function i(e){var t=e.option,u=e.options,n=e.labelKey,s=e.valueKey;return 0===u.filter(function(e){return e[n]===t[n]||e[s]===t[s]}).length}function a(e){var t=e.label;return!!t}function r(e){var t=e.label,u=e.labelKey,n=e.valueKey,s={};return s[n]=t,s[u]=t,s.className="Select-create-option-placeholder",s}function l(e){return'Create option "'+e+'"'}function p(e){var t=e.keyCode;switch(t){case 9:case 13:case 188:return!0}return!1}var d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var u=arguments[t];for(var n in u)Object.prototype.hasOwnProperty.call(u,n)&&(e[n]=u[n])}return e},c="undefined"!=typeof window?window.React:"undefined"!=typeof u?u.React:null,f=n(c),h=e("./Select"),E=n(h),y=e("./utils/defaultFilterOptions"),g=n(y),b=e("./utils/defaultMenuRenderer"),v=n(b),m=f["default"].createClass({displayName:"CreatableSelect",propTypes:{children:f["default"].PropTypes.func,filterOptions:f["default"].PropTypes.any,isOptionUnique:f["default"].PropTypes.func,isValidNewOption:f["default"].PropTypes.func,menuRenderer:f["default"].PropTypes.any,newOptionCreator:f["default"].PropTypes.func,onInputChange:f["default"].PropTypes.func,onInputKeyDown:f["default"].PropTypes.func,onNewOptionClick:f["default"].PropTypes.func,options:f["default"].PropTypes.array,promptTextCreator:f["default"].PropTypes.func,shouldKeyDownEventCreateNewOption:f["default"].PropTypes.func},statics:{isOptionUnique:i,isValidNewOption:a,newOptionCreator:r,promptTextCreator:l,shouldKeyDownEventCreateNewOption:p},getDefaultProps:function(){return{filterOptions:g["default"],isOptionUnique:i,isValidNewOption:a,menuRenderer:v["default"],newOptionCreator:r,promptTextCreator:l,shouldKeyDownEventCreateNewOption:p}},createNewOption:function(){var e=this.props,t=e.isValidNewOption,u=e.newOptionCreator,n=e.onNewOptionClick,s=e.options,o=void 0===s?[]:s;e.shouldKeyDownEventCreateNewOption;if(t({label:this.inputValue})){var i=u({label:this.inputValue,labelKey:this.labelKey,valueKey:this.valueKey}),a=this.isOptionUnique({option:i});a&&(n?n(i):(o.unshift(i),this.select.selectValue(i)))}},filterOptions:function C(){var e=this.props,C=e.filterOptions,t=e.isValidNewOption,u=(e.options,e.promptTextCreator),n=arguments[2]||[],s=C.apply(void 0,arguments)||[];if(t({label:this.inputValue})){var o=this.props.newOptionCreator,i=o({label:this.inputValue,labelKey:this.labelKey,valueKey:this.valueKey}),a=this.isOptionUnique({option:i,options:n.concat(s)});if(a){var r=u(this.inputValue);this._createPlaceholderOption=o({label:r,labelKey:this.labelKey,valueKey:this.valueKey}),s.unshift(this._createPlaceholderOption)}}return s},isOptionUnique:function F(e){var t=e.option,u=e.options,F=this.props.isOptionUnique;return u=u||this.select.filterOptions(),F({labelKey:this.labelKey,option:t,options:u,valueKey:this.valueKey})},menuRenderer:function O(e){var O=this.props.menuRenderer;return O(d({},e,{onSelect:this.onOptionSelect,selectValue:this.onOptionSelect}))},onInputChange:function w(e){var w=this.props.onInputChange;w&&w(e),this.inputValue=e},onInputKeyDown:function A(e){var t=this.props,u=t.shouldKeyDownEventCreateNewOption,A=t.onInputKeyDown,n=this.select.getFocusedOption();n&&n===this._createPlaceholderOption&&u({keyCode:e.keyCode})?(this.createNewOption(),e.preventDefault()):A&&A(e)},onOptionSelect:function(e,t){e===this._createPlaceholderOption?this.createNewOption():this.select.selectValue(e)},render:function(){var e=this,t=this.props,u=(t.newOptionCreator,t.shouldKeyDownEventCreateNewOption,s(t,["newOptionCreator","shouldKeyDownEventCreateNewOption"])),n=this.props.children;n||(n=o);var i=d({},u,{allowCreate:!0,filterOptions:this.filterOptions,menuRenderer:this.menuRenderer,onInputChange:this.onInputChange,onInputKeyDown:this.onInputKeyDown,ref:function(t){e.select=t,t&&(e.labelKey=t.props.labelKey,e.valueKey=t.props.valueKey)}});return n(i)}});t.exports=m}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Select":5,"./utils/defaultFilterOptions":9,"./utils/defaultMenuRenderer":10}],4:[function(e,t,u){(function(e){"use strict";function u(e){return e&&e.__esModule?e:{"default":e}}var n="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,s=u(n),o="undefined"!=typeof window?window.classNames:"undefined"!=typeof e?e.classNames:null,i=u(o),a=s["default"].createClass({displayName:"Option",propTypes:{children:s["default"].PropTypes.node,className:s["default"].PropTypes.string,instancePrefix:s["default"].PropTypes.string.isRequired,isDisabled:s["default"].PropTypes.bool,isFocused:s["default"].PropTypes.bool,isSelected:s["default"].PropTypes.bool,onFocus:s["default"].PropTypes.func,onSelect:s["default"].PropTypes.func,onUnfocus:s["default"].PropTypes.func,option:s["default"].PropTypes.object.isRequired,optionIndex:s["default"].PropTypes.number},blockEvent:function(e){e.preventDefault(),e.stopPropagation(),"A"===e.target.tagName&&"href"in e.target&&(e.target.target?window.open(e.target.href,e.target.target):window.location.href=e.target.href)},handleMouseDown:function(e){e.preventDefault(),e.stopPropagation(),this.props.onSelect(this.props.option,e)},handleMouseEnter:function(e){this.onFocus(e)},handleMouseMove:function(e){this.onFocus(e)},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},onFocus:function(e){this.props.isFocused||this.props.onFocus(this.props.option,e)},render:function(){var e=this.props,t=e.option,u=e.instancePrefix,n=e.optionIndex,o=(0,i["default"])(this.props.className,t.className);return t.disabled?s["default"].createElement("div",{className:o,onMouseDown:this.blockEvent,onClick:this.blockEvent},this.props.children):s["default"].createElement("div",{className:o,style:t.style,role:"option",onMouseDown:this.handleMouseDown,onMouseEnter:this.handleMouseEnter,onMouseMove:this.handleMouseMove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEnd,id:u+"-option-"+n,title:t.title},this.props.children)}});t.exports=a}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(e,t,u){(function(n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var u={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(u[n]=e[n]);return u}function i(e,t,u){return t in e?Object.defineProperty(e,t,{value:u,enumerable:!0,configurable:!0,writable:!0}):e[t]=u,e}function a(e){var t=typeof e;return"string"===t?e:"object"===t?JSON.stringify(e):"number"===t||"boolean"===t?String(e):""}Object.defineProperty(u,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var u=arguments[t];for(var n in u)Object.prototype.hasOwnProperty.call(u,n)&&(e[n]=u[n])}return e},l="undefined"!=typeof window?window.React:"undefined"!=typeof n?n.React:null,p=s(l),d="undefined"!=typeof window?window.ReactDOM:"undefined"!=typeof n?n.ReactDOM:null,c=s(d),f="undefined"!=typeof window?window.AutosizeInput:"undefined"!=typeof n?n.AutosizeInput:null,h=s(f),E="undefined"!=typeof window?window.classNames:"undefined"!=typeof n?n.classNames:null,y=s(E),g=e("./utils/defaultArrowRenderer"),b=s(g),v=e("./utils/defaultFilterOptions"),m=s(v),C=e("./utils/defaultMenuRenderer"),F=s(C),O=e("./utils/defaultClearRenderer"),w=s(O),A=e("./Async"),P=s(A),T=e("./AsyncCreatable"),D=s(T),V=e("./Creatable"),S=s(V),R=e("./Option"),B=s(R),x=e("./Value"),M=s(x),_=p["default"].PropTypes.oneOfType([p["default"].PropTypes.string,p["default"].PropTypes.node]),N=1,I=p["default"].createClass({displayName:"Select",propTypes:{addLabelText:p["default"].PropTypes.string,"aria-label":p["default"].PropTypes.string,"aria-labelledby":p["default"].PropTypes.string,arrowRenderer:p["default"].PropTypes.func,autoBlur:p["default"].PropTypes.bool,autofocus:p["default"].PropTypes.bool,autosize:p["default"].PropTypes.bool,backspaceRemoves:p["default"].PropTypes.bool,backspaceToRemoveMessage:p["default"].PropTypes.string,className:p["default"].PropTypes.string,clearAllText:_,clearRenderer:p["default"].PropTypes.func,clearValueText:_,clearable:p["default"].PropTypes.bool,deleteRemoves:p["default"].PropTypes.bool,delimiter:p["default"].PropTypes.string,disabled:p["default"].PropTypes.bool,escapeClearsValue:p["default"].PropTypes.bool,filterOption:p["default"].PropTypes.func,filterOptions:p["default"].PropTypes.any,ignoreAccents:p["default"].PropTypes.bool,ignoreCase:p["default"].PropTypes.bool,inputProps:p["default"].PropTypes.object,inputRenderer:p["default"].PropTypes.func,instanceId:p["default"].PropTypes.string,isLoading:p["default"].PropTypes.bool,joinValues:p["default"].PropTypes.bool,labelKey:p["default"].PropTypes.string,matchPos:p["default"].PropTypes.string,matchProp:p["default"].PropTypes.string,menuBuffer:p["default"].PropTypes.number,menuContainerStyle:p["default"].PropTypes.object,menuRenderer:p["default"].PropTypes.func,menuStyle:p["default"].PropTypes.object,multi:p["default"].PropTypes.bool,name:p["default"].PropTypes.string,noResultsText:_,onBlur:p["default"].PropTypes.func,onBlurResetsInput:p["default"].PropTypes.bool,onChange:p["default"].PropTypes.func,onClose:p["default"].PropTypes.func,onCloseResetsInput:p["default"].PropTypes.bool,onFocus:p["default"].PropTypes.func,onInputChange:p["default"].PropTypes.func,onInputKeyDown:p["default"].PropTypes.func,onMenuScrollToBottom:p["default"].PropTypes.func,onOpen:p["default"].PropTypes.func,onValueClick:p["default"].PropTypes.func,openAfterFocus:p["default"].PropTypes.bool,openOnFocus:p["default"].PropTypes.bool,optionClassName:p["default"].PropTypes.string,optionComponent:p["default"].PropTypes.func,optionRenderer:p["default"].PropTypes.func,options:p["default"].PropTypes.array,pageSize:p["default"].PropTypes.number,placeholder:_,required:p["default"].PropTypes.bool,resetValue:p["default"].PropTypes.any,scrollMenuIntoView:p["default"].PropTypes.bool,searchable:p["default"].PropTypes.bool,simpleValue:p["default"].PropTypes.bool,style:p["default"].PropTypes.object,tabIndex:p["default"].PropTypes.string,tabSelectsValue:p["default"].PropTypes.bool,value:p["default"].PropTypes.any,valueComponent:p["default"].PropTypes.func,valueKey:p["default"].PropTypes.string,valueRenderer:p["default"].PropTypes.func,wrapperStyle:p["default"].PropTypes.object},statics:{Async:P["default"],AsyncCreatable:D["default"],Creatable:S["default"]},getDefaultProps:function(){return{addLabelText:'Add "{label}"?',arrowRenderer:b["default"],autosize:!0,backspaceRemoves:!0,backspaceToRemoveMessage:"Press backspace to remove {label}",clearable:!0,clearAllText:"Clear all",clearRenderer:w["default"],clearValueText:"Clear value",deleteRemoves:!0,delimiter:",",disabled:!1,escapeClearsValue:!0,filterOptions:m["default"],ignoreAccents:!0,ignoreCase:!0,inputProps:{},isLoading:!1,joinValues:!1,labelKey:"label",matchPos:"any",matchProp:"any",menuBuffer:0,menuRenderer:F["default"],multi:!1,noResultsText:"No results found",onBlurResetsInput:!0,onCloseResetsInput:!0,openAfterFocus:!1,optionComponent:B["default"],pageSize:5,placeholder:"Select...",required:!1,scrollMenuIntoView:!0,searchable:!0,simpleValue:!1,tabSelectsValue:!0,valueComponent:M["default"],valueKey:"value"}},getInitialState:function(){return{inputValue:"",isFocused:!1,isOpen:!1,isPseudoFocused:!1,required:!1}},componentWillMount:function(){this._instancePrefix="react-select-"+(this.props.instanceId||++N)+"-";var e=this.getValueArray(this.props.value);this.props.required&&this.setState({required:this.handleRequired(e[0],this.props.multi)})},componentDidMount:function(){this.props.autofocus&&this.focus()},componentWillReceiveProps:function(e){var t=this.getValueArray(e.value,e);e.required&&this.setState({required:this.handleRequired(t[0],e.multi)})},componentWillUpdate:function(e,t){if(t.isOpen!==this.state.isOpen){this.toggleTouchOutsideEvent(t.isOpen);var u=t.isOpen?e.onOpen:e.onClose;u&&u()}},componentDidUpdate:function(e,t){if(this.menu&&this.focused&&this.state.isOpen&&!this.hasScrolledToOption){var u=c["default"].findDOMNode(this.focused),n=c["default"].findDOMNode(this.menu);n.scrollTop=u.offsetTop,this.hasScrolledToOption=!0}else this.state.isOpen||(this.hasScrolledToOption=!1);if(this._scrollToFocusedOptionOnUpdate&&this.focused&&this.menu){this._scrollToFocusedOptionOnUpdate=!1;var s=c["default"].findDOMNode(this.focused),o=c["default"].findDOMNode(this.menu),i=s.getBoundingClientRect(),a=o.getBoundingClientRect();(i.bottom>a.bottom||i.top<a.top)&&(o.scrollTop=s.offsetTop+s.clientHeight-o.offsetHeight)}if(this.props.scrollMenuIntoView&&this.menuContainer){var r=this.menuContainer.getBoundingClientRect();window.innerHeight<r.bottom+this.props.menuBuffer&&window.scrollBy(0,r.bottom+this.props.menuBuffer-window.innerHeight)}e.disabled!==this.props.disabled&&(this.setState({isFocused:!1}),this.closeMenu())},componentWillUnmount:function(){!document.removeEventListener&&document.detachEvent?document.detachEvent("ontouchstart",this.handleTouchOutside):document.removeEventListener("touchstart",this.handleTouchOutside)},toggleTouchOutsideEvent:function(e){e?!document.addEventListener&&document.attachEvent?document.attachEvent("ontouchstart",this.handleTouchOutside):document.addEventListener("touchstart",this.handleTouchOutside):!document.removeEventListener&&document.detachEvent?document.detachEvent("ontouchstart",this.handleTouchOutside):document.removeEventListener("touchstart",this.handleTouchOutside)},handleTouchOutside:function(e){this.wrapper&&!this.wrapper.contains(e.target)&&this.closeMenu()},focus:function(){this.input&&(this.input.focus(),this.props.openAfterFocus&&this.setState({isOpen:!0}))},blurInput:function(){this.input&&this.input.blur()},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchEndClearValue:function(e){this.dragging||this.clearValue(e)},handleMouseDown:function(e){if(!(this.props.disabled||"mousedown"===e.type&&0!==e.button)&&"INPUT"!==e.target.tagName){if(e.stopPropagation(),e.preventDefault(),!this.props.searchable)return this.focus(),this.setState({isOpen:!this.state.isOpen});if(this.state.isFocused){this.focus();var t=this.input;"function"==typeof t.getInput&&(t=t.getInput()),t.value="",this.setState({isOpen:!0,isPseudoFocused:!1})}else this._openAfterFocus=!0,this.focus()}},handleMouseDownOnArrow:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||this.state.isOpen&&(e.stopPropagation(),e.preventDefault(),this.closeMenu())},handleMouseDownOnMenu:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this._openAfterFocus=!0,this.focus())},closeMenu:function(){this.props.onCloseResetsInput?this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi,inputValue:""}):this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi,inputValue:this.state.inputValue}),this.hasScrolledToOption=!1},handleInputFocus:function(e){if(!this.props.disabled){var t=this.state.isOpen||this._openAfterFocus||this.props.openOnFocus;this.props.onFocus&&this.props.onFocus(e),this.setState({isFocused:!0,isOpen:t}),this._openAfterFocus=!1}},handleInputBlur:function(e){if(this.menu&&(this.menu===document.activeElement||this.menu.contains(document.activeElement)))return void this.focus();this.props.onBlur&&this.props.onBlur(e);var t={isFocused:!1,isOpen:!1,isPseudoFocused:!1};this.props.onBlurResetsInput&&(t.inputValue=""),this.setState(t)},handleInputChange:function(e){var t=e.target.value;if(this.state.inputValue!==e.target.value&&this.props.onInputChange){var u=this.props.onInputChange(t);null!=u&&"object"!=typeof u&&(t=""+u)}this.setState({isOpen:!0,isPseudoFocused:!1,inputValue:t})},handleKeyDown:function(e){if(!(this.props.disabled||"function"==typeof this.props.onInputKeyDown&&(this.props.onInputKeyDown(e),e.defaultPrevented))){switch(e.keyCode){case 8:return void(!this.state.inputValue&&this.props.backspaceRemoves&&(e.preventDefault(),this.popValue()));case 9:if(e.shiftKey||!this.state.isOpen||!this.props.tabSelectsValue)return;return void this.selectFocusedOption();case 13:if(!this.state.isOpen)return;e.stopPropagation(),this.selectFocusedOption();break;case 27:this.state.isOpen?(this.closeMenu(),e.stopPropagation()):this.props.clearable&&this.props.escapeClearsValue&&(this.clearValue(e),e.stopPropagation());break;case 38:this.focusPreviousOption();break;case 40:this.focusNextOption();break;case 33:this.focusPageUpOption();break;case 34:this.focusPageDownOption();break;case 35:if(e.shiftKey)return;this.focusEndOption();break;case 36:if(e.shiftKey)return;this.focusStartOption();break;case 46:return void(!this.state.inputValue&&this.props.deleteRemoves&&(e.preventDefault(),this.popValue()));default:return}e.preventDefault()}},handleValueClick:function(e,t){this.props.onValueClick&&this.props.onValueClick(e,t)},handleMenuScroll:function(e){if(this.props.onMenuScrollToBottom){var t=e.target;t.scrollHeight>t.offsetHeight&&!(t.scrollHeight-t.offsetHeight-t.scrollTop)&&this.props.onMenuScrollToBottom()}},handleRequired:function(e,t){return!e||(t?0===e.length:0===Object.keys(e).length)},getOptionLabel:function(e){return e[this.props.labelKey]},getValueArray:function(e,t){var u=this,n="object"==typeof t?t:this.props;if(n.multi){if("string"==typeof e&&(e=e.split(n.delimiter)),!Array.isArray(e)){if(null===e||void 0===e)return[];e=[e]}return e.map(function(e){return u.expandValue(e,n)}).filter(function(e){return e})}var s=this.expandValue(e,n);return s?[s]:[]},expandValue:function(e,t){var u=typeof e;if("string"!==u&&"number"!==u&&"boolean"!==u)return e;var n=t.options,s=t.valueKey;if(n)for(var o=0;o<n.length;o++)if(n[o][s]===e)return n[o]},setValue:function(e){var t=this;if(this.props.autoBlur&&this.blurInput(),this.props.onChange){if(this.props.required){var u=this.handleRequired(e,this.props.multi);this.setState({required:u})}this.props.simpleValue&&e&&(e=this.props.multi?e.map(function(e){return e[t.props.valueKey]}).join(this.props.delimiter):e[this.props.valueKey]),this.props.onChange(e)}},selectValue:function(e){var t=this;this.hasScrolledToOption=!1,this.props.multi?this.setState({inputValue:"",focusedIndex:null},function(){t.addValue(e)}):this.setState({isOpen:!1,inputValue:"",isPseudoFocused:this.state.isFocused},function(){t.setValue(e)})},addValue:function(e){var t=this.getValueArray(this.props.value),u=this._visibleOptions.filter(function(e){return!e.disabled}),n=u.indexOf(e);this.setValue(t.concat(e)),u.length-1===n?this.focusOption(u[n-1]):u.length>n&&this.focusOption(u[n+1])},popValue:function(){var e=this.getValueArray(this.props.value);e.length&&e[e.length-1].clearableValue!==!1&&this.setValue(e.slice(0,e.length-1))},removeValue:function(e){var t=this.getValueArray(this.props.value);this.setValue(t.filter(function(t){return t!==e})),this.focus()},clearValue:function(e){e&&"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this.setValue(this.getResetValue()),this.setState({isOpen:!1,inputValue:""},this.focus))},getResetValue:function(){return void 0!==this.props.resetValue?this.props.resetValue:this.props.multi?[]:null},focusOption:function(e){this.setState({focusedOption:e})},focusNextOption:function(){this.focusAdjacentOption("next")},focusPreviousOption:function(){this.focusAdjacentOption("previous")},focusPageUpOption:function(){this.focusAdjacentOption("page_up")},focusPageDownOption:function(){this.focusAdjacentOption("page_down")},focusStartOption:function(){this.focusAdjacentOption("start")},focusEndOption:function(){this.focusAdjacentOption("end")},focusAdjacentOption:function(e){var t=this._visibleOptions.map(function(e,t){return{option:e,index:t}}).filter(function(e){return!e.option.disabled});if(this._scrollToFocusedOptionOnUpdate=!0,!this.state.isOpen)return void this.setState({isOpen:!0,inputValue:"",focusedOption:this._focusedOption||(t.length?t["next"===e?0:t.length-1].option:null)});if(t.length){for(var u=-1,n=0;n<t.length;n++)if(this._focusedOption===t[n].option){u=n;break}if("next"===e&&u!==-1)u=(u+1)%t.length;else if("previous"===e)u>0?u-=1:u=t.length-1;else if("start"===e)u=0;else if("end"===e)u=t.length-1;else if("page_up"===e){var s=u-this.props.pageSize;u=s<0?0:s}else if("page_down"===e){var s=u+this.props.pageSize;u=s>t.length-1?t.length-1:s}u===-1&&(u=0),this.setState({focusedIndex:t[u].index,focusedOption:t[u].option})}},getFocusedOption:function(){return this._focusedOption},getInputValue:function(){return this.state.inputValue},selectFocusedOption:function(){if(this._focusedOption)return this.selectValue(this._focusedOption)},renderLoading:function(){if(this.props.isLoading)return p["default"].createElement("span",{className:"Select-loading-zone","aria-hidden":"true"},p["default"].createElement("span",{className:"Select-loading"}))},renderValue:function(e,t){var u=this,n=this.props.valueRenderer||this.getOptionLabel,s=this.props.valueComponent;if(!e.length)return this.state.inputValue?null:p["default"].createElement("div",{className:"Select-placeholder"},this.props.placeholder);var o=this.props.onValueClick?this.handleValueClick:null;return this.props.multi?e.map(function(e,t){return p["default"].createElement(s,{id:u._instancePrefix+"-value-"+t,instancePrefix:u._instancePrefix,disabled:u.props.disabled||e.clearableValue===!1,key:"value-"+t+"-"+e[u.props.valueKey],onClick:o,onRemove:u.removeValue,value:e},n(e,t),p["default"].createElement("span",{className:"Select-aria-only"}," "))}):this.state.inputValue?void 0:(t&&(o=null),p["default"].createElement(s,{id:this._instancePrefix+"-value-item",disabled:this.props.disabled,instancePrefix:this._instancePrefix,onClick:o,value:e[0]},n(e[0])))},renderInput:function(e,t){var u,n=this,s=(0,y["default"])("Select-input",this.props.inputProps.className),a=!!this.state.isOpen,l=(0,y["default"])((u={},i(u,this._instancePrefix+"-list",a),i(u,this._instancePrefix+"-backspace-remove-message",this.props.multi&&!this.props.disabled&&this.state.isFocused&&!this.state.inputValue),u)),d=r({},this.props.inputProps,{role:"combobox","aria-expanded":""+a,"aria-owns":l,"aria-haspopup":""+a,"aria-activedescendant":a?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value","aria-labelledby":this.props["aria-labelledby"],"aria-label":this.props["aria-label"],className:s,tabIndex:this.props.tabIndex,onBlur:this.handleInputBlur,onChange:this.handleInputChange,onFocus:this.handleInputFocus,ref:function(e){return n.input=e},required:this.state.required,value:this.state.inputValue});if(this.props.inputRenderer)return this.props.inputRenderer(d);if(this.props.disabled||!this.props.searchable){var c=this.props.inputProps,f=(c.inputClassName,o(c,["inputClassName"]));return p["default"].createElement("div",r({},f,{role:"combobox","aria-expanded":a,"aria-owns":a?this._instancePrefix+"-list":this._instancePrefix+"-value","aria-activedescendant":a?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value",className:s,tabIndex:this.props.tabIndex||0,onBlur:this.handleInputBlur,onFocus:this.handleInputFocus,ref:function(e){return n.input=e},"aria-readonly":""+!!this.props.disabled,style:{border:0,width:1,display:"inline-block"}}))}return this.props.autosize?p["default"].createElement(h["default"],r({},d,{minWidth:"5"})):p["default"].createElement("div",{className:s},p["default"].createElement("input",d))},renderClear:function(){if(this.props.clearable&&this.props.value&&0!==this.props.value&&(!this.props.multi||this.props.value.length)&&!this.props.disabled&&!this.props.isLoading){var e=this.props.clearRenderer();return p["default"].createElement("span",{className:"Select-clear-zone",title:this.props.multi?this.props.clearAllText:this.props.clearValueText,"aria-label":this.props.multi?this.props.clearAllText:this.props.clearValueText,onMouseDown:this.clearValue,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEndClearValue},e)}},renderArrow:function(){var e=this.handleMouseDownOnArrow,t=this.state.isOpen,u=this.props.arrowRenderer({onMouseDown:e,isOpen:t});return p["default"].createElement("span",{className:"Select-arrow-zone",onMouseDown:e},u)},filterOptions:function K(e){var t=this.state.inputValue,u=this.props.options||[];if(this.props.filterOptions){var K="function"==typeof this.props.filterOptions?this.props.filterOptions:m["default"];return K(u,t,e,{filterOption:this.props.filterOption,ignoreAccents:this.props.ignoreAccents,ignoreCase:this.props.ignoreCase,labelKey:this.props.labelKey,matchPos:this.props.matchPos,matchProp:this.props.matchProp,valueKey:this.props.valueKey})}return u},onOptionRef:function(e,t){t&&(this.focused=e)},renderMenu:function(e,t,u){return e&&e.length?this.props.menuRenderer({focusedOption:u,focusOption:this.focusOption, instancePrefix:this._instancePrefix,labelKey:this.props.labelKey,onFocus:this.focusOption,onSelect:this.selectValue,optionClassName:this.props.optionClassName,optionComponent:this.props.optionComponent,optionRenderer:this.props.optionRenderer||this.getOptionLabel,options:e,selectValue:this.selectValue,valueArray:t,valueKey:this.props.valueKey,onOptionRef:this.onOptionRef}):this.props.noResultsText?p["default"].createElement("div",{className:"Select-noresults"},this.props.noResultsText):null},renderHiddenField:function(e){var t=this;if(this.props.name){if(this.props.joinValues){var u=e.map(function(e){return a(e[t.props.valueKey])}).join(this.props.delimiter);return p["default"].createElement("input",{type:"hidden",ref:function(e){return t.value=e},name:this.props.name,value:u,disabled:this.props.disabled})}return e.map(function(e,u){return p["default"].createElement("input",{key:"hidden."+u,type:"hidden",ref:"value"+u,name:t.props.name,value:a(e[t.props.valueKey]),disabled:t.props.disabled})})}},getFocusableOptionIndex:function(e){var t=this._visibleOptions;if(!t.length)return null;var u=this.state.focusedOption||e;if(u&&!u.disabled){var n=t.indexOf(u);if(n!==-1)return n}for(var s=0;s<t.length;s++)if(!t[s].disabled)return s;return null},renderOuter:function(e,t,u){var n=this,s=this.renderMenu(e,t,u);return s?p["default"].createElement("div",{ref:function(e){return n.menuContainer=e},className:"Select-menu-outer",style:this.props.menuContainerStyle},p["default"].createElement("div",{ref:function(e){return n.menu=e},role:"listbox",className:"Select-menu",id:this._instancePrefix+"-list",style:this.props.menuStyle,onScroll:this.handleMenuScroll,onMouseDown:this.handleMouseDownOnMenu},s)):null},render:function(){var e=this,t=this.getValueArray(this.props.value),u=this._visibleOptions=this.filterOptions(this.props.multi?this.getValueArray(this.props.value):null),n=this.state.isOpen;this.props.multi&&!u.length&&t.length&&!this.state.inputValue&&(n=!1);var s=this.getFocusableOptionIndex(t[0]),o=null;o=null!==s?this._focusedOption=u[s]:this._focusedOption=null;var i=(0,y["default"])("Select",this.props.className,{"Select--multi":this.props.multi,"Select--single":!this.props.multi,"is-disabled":this.props.disabled,"is-focused":this.state.isFocused,"is-loading":this.props.isLoading,"is-open":n,"is-pseudo-focused":this.state.isPseudoFocused,"is-searchable":this.props.searchable,"has-value":t.length}),a=null;return this.props.multi&&!this.props.disabled&&t.length&&!this.state.inputValue&&this.state.isFocused&&this.props.backspaceRemoves&&(a=p["default"].createElement("span",{id:this._instancePrefix+"-backspace-remove-message",className:"Select-aria-only","aria-live":"assertive"},this.props.backspaceToRemoveMessage.replace("{label}",t[t.length-1][this.props.labelKey]))),p["default"].createElement("div",{ref:function(t){return e.wrapper=t},className:i,style:this.props.wrapperStyle},this.renderHiddenField(t),p["default"].createElement("div",{ref:function(t){return e.control=t},className:"Select-control",style:this.props.style,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleTouchEnd,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},p["default"].createElement("span",{className:"Select-multi-value-wrapper",id:this._instancePrefix+"-value"},this.renderValue(t,n),this.renderInput(t,s)),a,this.renderLoading(),this.renderClear(),this.renderArrow()),n?this.renderOuter(u,this.props.multi?null:t,o):null)}});u["default"]=I,t.exports=u["default"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Async":1,"./AsyncCreatable":2,"./Creatable":3,"./Option":4,"./Value":6,"./utils/defaultArrowRenderer":7,"./utils/defaultClearRenderer":8,"./utils/defaultFilterOptions":9,"./utils/defaultMenuRenderer":10}],6:[function(e,t,u){(function(e){"use strict";function u(e){return e&&e.__esModule?e:{"default":e}}var n="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,s=u(n),o="undefined"!=typeof window?window.classNames:"undefined"!=typeof e?e.classNames:null,i=u(o),a=s["default"].createClass({displayName:"Value",propTypes:{children:s["default"].PropTypes.node,disabled:s["default"].PropTypes.bool,id:s["default"].PropTypes.string,onClick:s["default"].PropTypes.func,onRemove:s["default"].PropTypes.func,value:s["default"].PropTypes.object.isRequired},handleMouseDown:function(e){if("mousedown"!==e.type||0===e.button)return this.props.onClick?(e.stopPropagation(),void this.props.onClick(this.props.value,e)):void(this.props.value.href&&e.stopPropagation())},onRemove:function(e){e.preventDefault(),e.stopPropagation(),this.props.onRemove(this.props.value)},handleTouchEndRemove:function(e){this.dragging||this.onRemove(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},renderRemoveIcon:function(){if(!this.props.disabled&&this.props.onRemove)return s["default"].createElement("span",{className:"Select-value-icon","aria-hidden":"true",onMouseDown:this.onRemove,onTouchEnd:this.handleTouchEndRemove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},"×")},renderLabel:function(){var e="Select-value-label";return this.props.onClick||this.props.value.href?s["default"].createElement("a",{className:e,href:this.props.value.href,target:this.props.value.target,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleMouseDown},this.props.children):s["default"].createElement("span",{className:e,role:"option","aria-selected":"true",id:this.props.id},this.props.children)},render:function(){return s["default"].createElement("div",{className:(0,i["default"])("Select-value",this.props.value.className),style:this.props.value.style,title:this.props.value.title},this.renderRemoveIcon(),this.renderLabel())}});t.exports=a}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(e,t,u){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function s(e){var t=e.onMouseDown;return i["default"].createElement("span",{className:"Select-arrow",onMouseDown:t})}Object.defineProperty(u,"__esModule",{value:!0}),u["default"]=s;var o="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,i=n(o);t.exports=u["default"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],8:[function(e,t,u){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function s(){return i["default"].createElement("span",{className:"Select-clear",dangerouslySetInnerHTML:{__html:"&times;"}})}Object.defineProperty(u,"__esModule",{value:!0}),u["default"]=s;var o="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,i=n(o);t.exports=u["default"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],9:[function(e,t,u){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function s(e,t,u,n){var s=this;return n.ignoreAccents&&(t=(0,i["default"])(t)),n.ignoreCase&&(t=t.toLowerCase()),u&&(u=u.map(function(e){return e[n.valueKey]})),e.filter(function(e){if(u&&u.indexOf(e[n.valueKey])>-1)return!1;if(n.filterOption)return n.filterOption.call(s,e,t);if(!t)return!0;var o=String(e[n.valueKey]),a=String(e[n.labelKey]);return n.ignoreAccents&&("label"!==n.matchProp&&(o=(0,i["default"])(o)),"value"!==n.matchProp&&(a=(0,i["default"])(a))),n.ignoreCase&&("label"!==n.matchProp&&(o=o.toLowerCase()),"value"!==n.matchProp&&(a=a.toLowerCase())),"start"===n.matchPos?"label"!==n.matchProp&&o.substr(0,t.length)===t||"value"!==n.matchProp&&a.substr(0,t.length)===t:"label"!==n.matchProp&&o.indexOf(t)>=0||"value"!==n.matchProp&&a.indexOf(t)>=0})}var o=e("./stripDiacritics"),i=n(o);t.exports=s},{"./stripDiacritics":11}],10:[function(e,t,u){(function(e){"use strict";function u(e){return e&&e.__esModule?e:{"default":e}}function n(e){var t=e.focusedOption,u=e.instancePrefix,n=(e.labelKey,e.onFocus),s=e.onSelect,i=e.optionClassName,r=e.optionComponent,l=e.optionRenderer,p=e.options,d=e.valueArray,c=e.valueKey,f=e.onOptionRef,h=r;return p.map(function(e,r){var p=d&&d.indexOf(e)>-1,E=e===t,y=(0,o["default"])(i,{"Select-option":!0,"is-selected":p,"is-focused":E,"is-disabled":e.disabled});return a["default"].createElement(h,{className:y,instancePrefix:u,isDisabled:e.disabled,isFocused:E,isSelected:p,key:"option-"+r+"-"+e[c],onFocus:n,onSelect:s,option:e,optionIndex:r,ref:function(e){f(e,E)}},l(e,r))})}var s="undefined"!=typeof window?window.classNames:"undefined"!=typeof e?e.classNames:null,o=u(s),i="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,a=u(i);t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],11:[function(e,t,u){"use strict";var n=[{base:"A",letters:/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},{base:"AA",letters:/[\uA732]/g},{base:"AE",letters:/[\u00C6\u01FC\u01E2]/g},{base:"AO",letters:/[\uA734]/g},{base:"AU",letters:/[\uA736]/g},{base:"AV",letters:/[\uA738\uA73A]/g},{base:"AY",letters:/[\uA73C]/g},{base:"B",letters:/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},{base:"C",letters:/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},{base:"D",letters:/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},{base:"DZ",letters:/[\u01F1\u01C4]/g},{base:"Dz",letters:/[\u01F2\u01C5]/g},{base:"E",letters:/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},{base:"F",letters:/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},{base:"G",letters:/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},{base:"H",letters:/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},{base:"I",letters:/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},{base:"J",letters:/[\u004A\u24BF\uFF2A\u0134\u0248]/g},{base:"K",letters:/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},{base:"L",letters:/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},{base:"LJ",letters:/[\u01C7]/g},{base:"Lj",letters:/[\u01C8]/g},{base:"M",letters:/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},{base:"N",letters:/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},{base:"NJ",letters:/[\u01CA]/g},{base:"Nj",letters:/[\u01CB]/g},{base:"O",letters:/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},{base:"OI",letters:/[\u01A2]/g},{base:"OO",letters:/[\uA74E]/g},{base:"OU",letters:/[\u0222]/g},{base:"P",letters:/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},{base:"Q",letters:/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},{base:"R",letters:/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},{base:"S",letters:/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},{base:"T",letters:/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},{base:"TZ",letters:/[\uA728]/g},{base:"U",letters:/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},{base:"V",letters:/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},{base:"VY",letters:/[\uA760]/g},{base:"W",letters:/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},{base:"X",letters:/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},{base:"Y",letters:/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},{base:"Z",letters:/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},{base:"a",letters:/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},{base:"aa",letters:/[\uA733]/g},{base:"ae",letters:/[\u00E6\u01FD\u01E3]/g},{base:"ao",letters:/[\uA735]/g},{base:"au",letters:/[\uA737]/g},{base:"av",letters:/[\uA739\uA73B]/g},{base:"ay",letters:/[\uA73D]/g},{base:"b",letters:/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},{base:"c",letters:/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},{base:"d",letters:/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},{base:"dz",letters:/[\u01F3\u01C6]/g},{base:"e",letters:/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},{base:"f",letters:/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},{base:"g",letters:/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},{base:"h",letters:/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},{base:"hv",letters:/[\u0195]/g},{base:"i",letters:/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},{base:"j",letters:/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},{base:"k",letters:/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},{base:"l",letters:/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},{base:"lj",letters:/[\u01C9]/g},{base:"m",letters:/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},{base:"n",letters:/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},{base:"nj",letters:/[\u01CC]/g},{base:"o",letters:/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},{base:"oi",letters:/[\u01A3]/g},{base:"ou",letters:/[\u0223]/g},{base:"oo",letters:/[\uA74F]/g},{base:"p",letters:/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},{base:"q",letters:/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},{base:"r",letters:/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},{base:"s",letters:/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},{base:"t",letters:/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},{base:"tz",letters:/[\uA729]/g},{base:"u",letters:/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},{base:"v",letters:/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},{base:"vy",letters:/[\uA761]/g},{base:"w",letters:/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},{base:"x",letters:/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},{base:"y",letters:/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},{base:"z",letters:/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}];t.exports=function(e){for(var t=0;t<n.length;t++)e=e.replace(n[t].letters,n[t].base);return e}},{}]},{},[5])(5)});
client/me/payment-methods/controller.js
tinkertinker/wp-calypso
/** * External dependencies */ import React from 'react'; /** * Internal dependencies */ import AddCreditCard from 'me/payment-methods/add-credit-card'; import * as paths from './paths'; import { recordPageView, renderPage } from 'lib/react-helpers'; export function addCreditCard( context ) { recordPageView( paths.addCreditCard(), 'Payment Methods', 'Add Credit Card' ); renderPage( context, <AddCreditCard /> ); }
test/integration/client-navigation/pages/head.js
zeit/next.js
import React from 'react' import Head from 'next/head' export default () => ( <div> <Head> {/* this will not render */} <meta charSet="utf-8" /> {/* this will get rendered */} <meta charSet="iso-8859-5" /> {/* this will not render */} <meta name="viewport" content="width=device-width" /> {/* this will override the default */} <meta name="viewport" content="width=device-width,initial-scale=1" /> <meta content="my meta" /> {/* this will not render the content prop */} <meta name="empty-content" content={undefined} /> {/* allow duplicates for specific tags */} <meta property="article:tag" content="tag1" key="tag1key" /> <meta property="article:tag" content="tag2" key="tag2key" /> <meta property="dedupe:tag" content="tag3" key="same-key" /> <meta property="dedupe:tag" content="tag4" key="same-key" /> <meta property="og:image" content="ogImageTag1" key="ogImageTag1Key" /> <meta property="og:image" content="ogImageTag2" key="ogImageTag2Key" /> <meta property="og:image:alt" content="ogImageAltTag1" key="ogImageAltTag1Key" /> <meta property="og:image:alt" content="ogImageAltTag2" key="ogImageAltTag2Key" /> <meta property="og:image:width" content="ogImageWidthTag1" key="ogImageWidthTag1Key" /> <meta property="og:image:width" content="ogImageWidthTag2" key="ogImageWidthTag2Key" /> <meta property="og:image:height" content="ogImageHeightTag1" key="ogImageHeightTag1Key" /> <meta property="og:image:height" content="ogImageHeightTag2" key="ogImageHeightTag2Key" /> <meta property="og:image:type" content="ogImageTypeTag1" key="ogImageTypeTag1Key" /> <meta property="og:image:type" content="ogImageTypeTag2" key="ogImageTypeTag2Key" /> <meta property="og:image:secure_url" content="ogImageSecureUrlTag1" key="ogImageSecureUrlTag1Key" /> <meta property="og:image:secure_url" content="ogImageSecureUrlTag2" key="ogImageSecureUrlTag2Key" /> <meta property="og:image:url" content="ogImageUrlTag1" key="ogImageUrlTag1Key" /> <meta property="og:image:url" content="ogImageUrlTag2" key="ogImageUrlTag2Key" /> <meta property="fb:pages" content="fbpages1" /> <meta property="fb:pages" content="fbpages2" /> {/* both meta tags will be rendered since they use unique keys */} <meta name="citation_author" content="authorName1" key="citationAuthorTag1" /> <meta name="citation_author" content="authorName2" key="citationAuthorTag2" /> <React.Fragment> <title>Fragment title</title> <meta content="meta fragment" /> </React.Fragment> {/* the following 2 link tags will both be rendered */} <link rel="stylesheet" href="/dup-style.css" /> <link rel="stylesheet" href="/dup-style.css" /> {/* only one tag will be rendered as they have the same key */} <link rel="stylesheet" href="dedupe-style.css" key="my-style" /> <link rel="stylesheet" href="dedupe-style.css" key="my-style" /> {/* this should not execute twice on the client */} <script src="/test-async.js" async></script> {/* this should not execute twice on the client (intentionally sets defer to `yas` to test boolean coercion) */} <script src="/test-defer.js" defer="yas"></script> {/* such style can be used for alternate links on _app vs individual pages */} {['pl', 'en'].map((language) => ( <link rel="alternate" key={language} hrefLang={language} href={'/first/' + language} /> ))} {['pl', 'en'].map((language) => ( <link rel="alternate" key={language} hrefLang={language} href={'/last/' + language} /> ))} </Head> <h1>I can have meta tags</h1> </div> )
ajax/libs/6to5/1.14.3/browser-polyfill.js
GaryChamberlain/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(require,module,exports){(function(global){var ensureSymbol=function(key){Symbol[key]=Symbol[key]||Symbol()};var ensureProto=function(Constructor,key,val){var proto=Constructor.prototype;proto[key]=proto[key]||val};if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("./transformation/transformers/es6-generators/runtime");ensureSymbol("referenceGet");ensureSymbol("referenceSet");ensureSymbol("referenceDelete");ensureProto(Function,Symbol.referenceGet,function(){return this});ensureProto(Map,Symbol.referenceGet,Map.prototype.get);ensureProto(Map,Symbol.referenceSet,Map.prototype.set);ensureProto(Map,Symbol.referenceDelete,Map.prototype.delete);if(global.WeakMap){ensureProto(WeakMap,Symbol.referenceGet,WeakMap.prototype.get);ensureProto(WeakMap,Symbol.referenceSet,WeakMap.prototype.set);ensureProto(WeakMap,Symbol.referenceDelete,WeakMap.prototype.delete)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transformers/es6-generators/runtime":2,"es6-shim":4,"es6-symbol/implement":5}],2:[function(require,module,exports){(function(global){var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var runtime=global.regeneratorRuntime=exports;var hasOwn=Object.prototype.hasOwnProperty;var wrap=runtime.wrap=function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])};var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};var GF=function GeneratorFunction(){};var GFp=function GeneratorFunctionPrototype(){};var Gp=GFp.prototype=Generator.prototype;(GFp.constructor=GF).prototype=Gp.constructor=GFp;var GFName="GeneratorFunction";if(GF.name!==GFName)GF.name=GFName;if(GF.name!==GFName)throw new Error(GFName+" renamed?");runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GF.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var info;var value;try{info=this(arg);value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;var info;if(delegate){try{info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;var thrown;if(record.type==="throw"){thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],3:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],4:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}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){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");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;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 defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};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};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";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$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};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")}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){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="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(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){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)){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){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.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;if(v!==v){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){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}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("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){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("");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);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){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(_){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>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){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(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={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]:void 0;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]: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},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;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}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="…".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n \f\r   ᠎    ","          \u2028","\u2029"].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,"")}})}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(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<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?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){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}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);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}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}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 ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[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.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]: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[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},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[1];for(var i=0;i<length;i++){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")}};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}if(Array.prototype.keys&&Array.prototype.entries&&!Array.prototype.values&&Array.prototype[$iterator$]){defineProperties(Array.prototype,{values:Array.prototype[$iterator$]})}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});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){return value!==value}});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)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof 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,{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)},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{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}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.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){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}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){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;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(4294967295,5)!==-5){Math.imul=MathShims.imul }var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};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]);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")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){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(){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)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){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;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){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}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;defineProperties(Promise,{"@@create":function(obj){var constructor=this;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}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};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)}}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){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);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);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}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}();defineProperties(globals,{Promise:PromiseShim});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}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}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"]);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"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){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){i=i.prev}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}}}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);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});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;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){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}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){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){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}}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}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){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}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(){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()});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;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){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}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){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.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}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){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([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:3}],5:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":6,"./polyfill":21,"es5-ext/global":8}],6:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],7:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":9,"es5-ext/object/is-callable":12,"es5-ext/object/normalize-options":16,"es5-ext/string/#/contains":18}],8:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],9:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":10,"./shim":11}],10:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],11:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":13,"../valid-value":17}],12:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],13:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],15:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],16:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":9}],17:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],18:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],20:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],21:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:7}]},{},[1]);
js/player/ButtonPanel.js
GyrosOfWar/podcaster-frontend
import React from 'react' import { Button, Glyphicon, ButtonGroup } from 'react-bootstrap' const ButtonPanel = React.createClass({ getDefaultProps: function() { return { currentSongIndex: 0, songCount: 0 }; }, render: function() { var isPlaying = this.props.isPlaying; var isPause = this.props.isPause; var isLoading = this.props.isLoading; var isShowPlayBtn = !isPlaying || isPause; var buttonClickHandler = isShowPlayBtn ? this.props.onPlayBtnClick : this.props.onPauseBtnClick; var iconName; var iconClasses = ""; if (isLoading) { iconName = "refresh"; iconClasses = "audio-refresh-animate"; } else { iconName = isShowPlayBtn ? "play" : "pause"; } var songIndex = this.props.currentSongIndex; var buttonPanelClasses = "audio-button-panel pull-left"; if (this.props.songCount < 2) { return ( <ButtonGroup className={buttonPanelClasses}> <Button bsSize="small" onClick={buttonClickHandler}> <Glyphicon className={iconClasses} glyph={iconName} /> </Button> </ButtonGroup> ); } else { var nextButtonClass = songIndex == this.props.songCount - 1 ? "disabled" : ""; return ( <ButtonGroup className={buttonPanelClasses}> <Button bsSize="small" onClick={this.props.onPrevBtnClick}> <Glyphicon glyph="step-backward" /> </Button> <Button bsSize="small" onClick={buttonClickHandler}> <Glyphicon className={iconClasses} glyph={iconName} /> </Button> <Button bsSize="small" onClick={this.props.onNextBtnClick} className={nextButtonClass}> <Glyphicon glyph="step-forward" /> </Button> </ButtonGroup> ); } } }) export default ButtonPanel
stories/components/modal/index.js
tskuse/operationcode_frontend
import React, { Component } from 'react'; import { storiesOf } from '@storybook/react'; import Modal from 'shared/components/modal/modal'; class ComponentWithModal extends Component { constructor() { super(); this.state = { isModalOpened: false, }; } handleOpen = () => { this.setState({ isModalOpened: true }); } handleClose = () => { this.setState({ isModalOpened: false }); } render() { return ( <div> <button type="button" onClick={this.handleOpen} > Open Modal </button> <Modal isOpen={this.state.isModalOpened} onRequestClose={this.handleClose} title="Title" > <span>This is modal content</span> </Modal> </div> ); } } storiesOf('shared/components/modal', module) .add('Default', () => ( <ComponentWithModal /> ));
src/components/Magic/MagicDisplay.js
KageEnterprises/weed-wizard
import PropTypes from 'prop-types'; import React from 'react'; import NumberFormat from 'react-number-format'; import { Card, CardContent, Checkbox, Chip, List, ListItem, ListItemText, Typography } from '@material-ui/core'; import { withStyles } from '@material-ui/core/styles'; import { contextPropTypes } from '../../AppContext'; import { getSpellById } from '../../Magic/MagicUtils'; import { listStyles } from '../../sharedStyles'; const styles = { body2: { '& .right': { float: 'right' } } }; class MagicDisplay extends React.Component { static propTypes = { player: contextPropTypes.playerShape, toggleSpell: PropTypes.func }; spellIsDisabled = spell => { return this.props.player.highness <= spell.cost; }; spellListMapping = (spell, classes) => { const { toggleSpell } = this.props; const active = spell.type === 'passive' ? spell.active : false; return ( <ListItem key={ spell.id } button classes={ { root: classes.listItem__root } } disabled={ this.spellIsDisabled(spell) } onClick={ () => { toggleSpell(spell) } }> {spell.type === 'passive' && ( <Checkbox checked={ active } classes={{ root: classes.checkbox__root }} onClick={ () => { } } /> ) } <ListItemText classes={ { root: classes.listItemText__root, secondary: classes.listItemText__secondary } } primary={ spell.name } secondary={ spell.description } /> <div> <NumberFormat decimalScale={ 2 } displayType='text' value={ spell.type === 'passive' ? spell.cost * 1000 : spell.cost } suffix={ spell.type === 'passive' ? '/s' : '' } renderText={ value => ( <Chip classes={ { label: classes.chip__label, root: classes.chip__root } } label={ value } /> )} /> </div> </ListItem> ); }; render() { const { classes, player } = this.props; const { spellsList } = player; const fullSpellsList = spellsList.map(SPELL => { return { ...getSpellById(SPELL.id), ...SPELL }; } ); const actionSpellsList = fullSpellsList .filter(SPELL => SPELL.type === 'action') .map(SPELL => this.spellListMapping(SPELL, classes) ); const passiveSpellsList = fullSpellsList .filter(SPELL => SPELL.type === 'passive') .map(SPELL => this.spellListMapping(SPELL, classes) ); return ( <Card> <CardContent> <Typography variant="headline"> Magic! </Typography> <Typography variant="subheading"> Spells You Know </Typography> <Typography classes={{ body2: classes.body2 }} variant="body2"> Passive Spells <span className="right">Cost</span> </Typography> <List> { passiveSpellsList } </List> <Typography classes={{ body2: classes.body2 }} variant="body2"> Action Spells <span className="right">Cost</span> </Typography> <List> { actionSpellsList } </List> </CardContent> </Card> ); } } export default withStyles({ ...listStyles, ...styles })(MagicDisplay);
ajax/libs/ember-data.js/1.13.7/ember-data.js
Teino1978-Corp/Teino1978-Corp-cdnjs
(function() { "use strict"; var ember$lib$main$$default = Ember; var ember$data$lib$system$object$polyfills$$keysFunc = Object.keys || Ember.keys; var ember$data$lib$system$object$polyfills$$create = Object.create || Ember.create; var ember$data$lib$adapters$errors$$EmberError = Ember.Error; var ember$data$lib$adapters$errors$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$adapters$errors$$SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;/** @class AdapterError @namespace DS */ function ember$data$lib$adapters$errors$$AdapterError(errors, message) { message = message || "Adapter operation failed"; ember$data$lib$adapters$errors$$EmberError.call(this, message); this.errors = errors || [{ title: "Adapter Error", detail: message }]; } ember$data$lib$adapters$errors$$AdapterError.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$adapters$errors$$EmberError.prototype); /** 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: function() { // 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 */ function ember$data$lib$adapters$errors$$InvalidError(errors) { if (!Ember.isArray(errors)) { Ember.deprecate("`InvalidError` expects json-api formatted errors.", false, { id: "ds.errors.invalid-error-expects-json-api-format", until: "2.0.0" }); errors = ember$data$lib$adapters$errors$$errorsHashToArray(errors); } ember$data$lib$adapters$errors$$AdapterError.call(this, errors, "The adapter rejected the commit because it was invalid"); } ember$data$lib$adapters$errors$$InvalidError.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$adapters$errors$$AdapterError.prototype); /** @class TimeoutError @namespace DS */ function ember$data$lib$adapters$errors$$TimeoutError() { ember$data$lib$adapters$errors$$AdapterError.call(this, null, "The adapter operation timed out"); } ember$data$lib$adapters$errors$$TimeoutError.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$adapters$errors$$AdapterError.prototype); /** @class AbortError @namespace DS */ function ember$data$lib$adapters$errors$$AbortError() { ember$data$lib$adapters$errors$$AdapterError.call(this, null, "The adapter operation was aborted"); } ember$data$lib$adapters$errors$$AbortError.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$adapters$errors$$AdapterError.prototype); /** @private */ function ember$data$lib$adapters$errors$$errorsHashToArray(errors) { var out = []; if (Ember.isPresent(errors)) { ember$data$lib$adapters$errors$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(errors), function (key) { var messages = Ember.makeArray(errors[key]); for (var i = 0; i < messages.length; i++) { out.push({ title: "Invalid Attribute", detail: messages[i], source: { pointer: "/data/attributes/" + key } }); } }); } return out; } function ember$data$lib$adapters$errors$$errorsArrayToHash(errors) { var out = {}; if (Ember.isPresent(errors)) { ember$data$lib$adapters$errors$$forEach.call(errors, function (error) { if (error.source && error.source.pointer) { var key = error.source.pointer.match(ember$data$lib$adapters$errors$$SOURCE_POINTER_REGEXP); if (key) { key = key[2]; out[key] = out[key] || []; out[key].push(error.detail || error.title); } } }); } return out; } var ember$data$lib$system$adapter$$get = Ember.get; /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter` in the `app/adapters` folder: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...your code here }); ``` Model-specific adapters can be created by putting your adapter class in an `app/adapters/` + `model-name` + `.js` file of the application. ```app/adapters/post.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...Post-specific adapter code goes here }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `findRecord()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `query()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ var ember$data$lib$system$adapter$$Adapter = Ember.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. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `findRecord` implementation: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findRecord: function(store, type, id, snapshot) { var url = [type.modelName, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).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 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 DS from 'ember-data'; export default DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).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 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 DS from 'ember-data'; export default DS.Adapter.extend({ query: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @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 ```javascript App.ApplicationAdapter = DS.Adapter.extend({ queryRecord: function(store, typeClass, query) { var url = [type.typeKey, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).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 queryRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {String} id @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 generateIdForRecord: function(store, inputProperties) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @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: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function (snapshot, options) { return ember$data$lib$system$adapter$$get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, 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 DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, 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. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ updateRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, 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 DS from 'ember-data'; export default DS.Adapter.extend({ deleteRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, 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, /** Find multiple records at once if coalesceFindRequests is true. @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 */ /** 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. @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 record. @method shouldReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldReloadAll: function (store, snapshotRecordArray) { var modelName = snapshotRecordArray.type.modelName; Ember.deprecate('The default behavior of shouldReloadAll will change in Ember Data 2.0 to always return false when there is at least one "' + modelName + '" record in the store. If you would like to preserve the current behavior please override shouldReloadAll in your adapter:application and return true.', false, { id: 'ds.adapter.should-reload-all-default-behavior', until: '2.0.0' }); return true; }, /** 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. @method shouldBackgroundReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldBackgroundReloadRecord: function (store, snapshot) { Ember.deprecate('The default behavior of `shouldBackgroundReloadRecord` will change in Ember Data 2.0 to always return true. If you would like to preserve the current behavior please override `shouldBackgroundReloadRecord` in your adapter:application and return false.', false, { id: 'ds.adapter.should-background-reload-record-default-behavior', until: '2.0.0' }); return false; }, /** 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. @method shouldBackgroundReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldBackgroundReloadAll: function (store, snapshotRecordArray) { return true; } }); var ember$data$lib$system$adapter$$default = ember$data$lib$system$adapter$$Adapter; var ember$data$lib$system$map$$Map = Ember.Map; var ember$data$lib$system$map$$MapWithDefault = Ember.MapWithDefault; var ember$data$lib$system$map$$default = ember$data$lib$system$map$$Map; var ember$data$lib$adapters$build$url$mixin$$get = Ember.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 */ var ember$data$lib$adapters$build$url$mixin$$BuildURLMixin = Ember.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 'find': // The `find` case is deprecated return this.urlForFind(id, modelName, snapshot); case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName); case 'findQuery': // The `findQuery` case is deprecated return this.urlForFindQuery(query, modelName); case 'query': return this.urlForQuery(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName); 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 url = []; var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host'); var prefix = this.urlPrefix(); var path; 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; }, /** * @method urlForFind * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url * @deprecated Use [urlForFindRecord](#method_urlForFindRecord) instead */ urlForFind: ember$data$lib$adapters$build$url$mixin$$urlForFind, /** * @method urlForFind * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindRecord: function (id, modelName, snapshot) { if (this.urlForFind !== ember$data$lib$adapters$build$url$mixin$$urlForFind) { Ember.deprecate('BuildURLMixin#urlForFind has been deprecated and renamed to `urlForFindRecord`.', false, { id: 'ds.adapter.url-for-find-deprecated', until: '2.0.0' }); return this.urlForFind(id, modelName, snapshot); } return this._buildURL(modelName, id); }, /** * @method urlForFindAll * @param {String} modelName * @return {String} url */ urlForFindAll: function (modelName) { return this._buildURL(modelName); }, /** * @method urlForFindQuery * @param {Object} query * @param {String} modelName * @return {String} url * @deprecated Use [urlForQuery](#method_urlForQuery) instead */ urlForFindQuery: ember$data$lib$adapters$build$url$mixin$$urlForFindQuery, /** * @method urlForQuery * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQuery: function (query, modelName) { if (this.urlForFindQuery !== ember$data$lib$adapters$build$url$mixin$$urlForFindQuery) { Ember.deprecate('BuildURLMixin#urlForFindQuery has been deprecated and renamed to `urlForQuery`.', false, { id: 'ds.adapter.url-for-find-query-deprecated', until: '2.0.0' }); return this.urlForFindQuery(query, modelName); } return this._buildURL(modelName); }, /** * @method urlForFindMany * @param {Array} ids * @param {String} modelName * @param {Array} snapshots * @return {String} url */ urlForFindMany: function (ids, modelName, snapshots) { return this._buildURL(modelName); }, /** * @method urlForFindHasMany * @param {String} id * @param {String} modelName * @return {String} url */ urlForFindHasMany: function (id, modelName) { return this._buildURL(modelName, id); }, /** * @method urlForFindBelongTo * @param {String} id * @param {String} modelName * @return {String} url */ urlForFindBelongsTo: function (id, modelName) { return this._buildURL(modelName, id); }, /** * @method urlForCreateRecord * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForCreateRecord: function (modelName, snapshot) { return this._buildURL(modelName); }, /** * @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); }, /** * @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 = ember$data$lib$adapters$build$url$mixin$$get(this, 'host'); var namespace = ember$data$lib$adapters$build$url$mixin$$get(this, 'namespace'); var url = []; if (path) { // Protocol relative url //jscs:disable disallowEmptyBlocks if (/^\/\//.test(path)) {} else if (path.charAt(0) === '/') { //jscs:enable disallowEmptyBlocks if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } 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'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var camelized = Ember.String.camelize(modelName); return Ember.String.pluralize(camelized); } }); function ember$data$lib$adapters$build$url$mixin$$urlForFind(id, modelName, snapshot) { Ember.deprecate('BuildURLMixin#urlForFind has been deprecated and renamed to `urlForFindRecord`.', false, { id: 'ds.adapter.url-for-find-deprecated', until: '2.0.0' }); return this._buildURL(modelName, id); } function ember$data$lib$adapters$build$url$mixin$$urlForFindQuery(query, modelName) { Ember.deprecate('BuildURLMixin#urlForFindQuery has been deprecated and renamed to `urlForQuery`.', false, { id: 'ds.adapter.url-for-find-query-deprecated', until: '2.0.0' }); return this._buildURL(modelName); } var ember$data$lib$adapters$build$url$mixin$$default = ember$data$lib$adapters$build$url$mixin$$BuildURLMixin; var ember$data$lib$adapters$rest$adapter$$get = Ember.get; var ember$data$lib$adapters$rest$adapter$$set = Ember.set; var ember$data$lib$adapters$rest$adapter$$forEach = Ember.ArrayPolyfills.forEach;/** 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. ## 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 { "post": { "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" } ] } ``` ### 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 { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## 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 `App.Person` 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: function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }.property("session.authToken") }); ``` 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: function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }.property().volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ var ember$data$lib$adapters$rest$adapter$$RestAdapter = ember$data$lib$system$adapter$$default.extend(ember$data$lib$adapters$build$url$mixin$$default, { defaultSerializer: "-rest", /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.query('posts', { sort: 'price', category: 'pets' }); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams: function (obj) { var keys = ember$data$lib$system$object$polyfills$$keysFunc(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, /** 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 `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** 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' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** 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. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** @method find @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise @deprecated Use [findRecord](#method_findRecord) instead */ find: function (store, type, id, snapshot) { Ember.deprecate("RestAdapter#find has been deprecated and renamed to `findRecord`.", false, { id: "ds.adapter.find-renamed-to-find-record", until: "2.0.0" }); return this.ajax(this.buildURL(type.modelName, id, snapshot, "find"), "GET"); }, /** Called by the store in order to fetch the JSON for a given type and ID. The `findRecord` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: function (store, type, id, snapshot) { var find = ember$data$lib$adapters$rest$adapter$$RestAdapter.prototype.find; if (find !== this.find) { Ember.deprecate("RestAdapter#find has been deprecated and renamed to `findRecord`.", false, { id: "ds.adapter.find-renamed-to-find-record", until: "2.0.0" }); return this.find(store, type, id, snapshot); } return this.ajax(this.buildURL(type.modelName, id, snapshot, "findRecord"), "GET"); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function (store, type, sinceToken) { var query, url; if (sinceToken) { query = { since: sinceToken }; } url = this.buildURL(type.modelName, null, null, "findAll"); return this.ajax(url, "GET", { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise @deprecated Use [query](#method_query) instead */ findQuery: function (store, type, query) { Ember.deprecate("RestAdapter#findQuery has been deprecated and renamed to `query`.", false, { id: "ds.adapter.find-query-renamed-to-query", until: "2.0.0" }); var url = this.buildURL(type.modelName, null, null, "findQuery", query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, "GET", { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ query: function (store, type, query) { var findQuery = ember$data$lib$adapters$rest$adapter$$RestAdapter.prototype.findQuery; if (findQuery !== this.findQuery) { Ember.deprecate("RestAdapter#findQuery has been deprecated and renamed to `query`.", false, { id: "ds.adapter.find-query-renamed-to-query", until: "2.0.0" }); return this.findQuery(store, type, query); } var url = this.buildURL(type.modelName, null, null, "query", query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, "GET", { data: query }); }, /** Called by the store in order to fetch a JSON object for the record that matches a particular query. The `queryRecord` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method queryRecord @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: function (store, type, query) { var url = this.buildURL(type.modelName, null, null, "queryRecord", query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, "GET", { data: query }); }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, type, ids, snapshots) { var url = this.buildURL(type.modelName, ids, snapshots, "findMany"); return this.ajax(url, "GET", { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany: function (store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, null, "findHasMany")); return this.ajax(url, "GET"); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo: function (store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, null, "findBelongsTo")); return this.ajax(url, "GET"); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function (store, type, snapshot) { 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 }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, type, snapshot) { 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 }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function (store, type, snapshot) { 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 var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (lastSegment === id) { expandedURL[expandedURL.length - 1] = ""; } else if (ember$data$lib$adapters$rest$adapter$$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, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @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) { var groups = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function () { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; ember$data$lib$adapters$rest$adapter$$forEach.call(snapshots, function (snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; ember$data$lib$adapters$rest$adapter$$forEach.call(group, 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); ember$data$lib$adapters$rest$adapter$$forEach.call(splitGroups, function (splitGroup) { groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Takes an ajax response, and returns an error payload. @method ajaxError @deprecated Use [handleResponse](#method_handleResponse) instead @param {Object} jqXHR @param {Object} responseText @param {Object} errorThrown @return {Object} jqXHR */ /** Takes an ajax response, and returns the json payload. @method ajaxSuccess @deprecated Use [handleResponse](#method_handleResponse) instead @param {Object} jqXHR @param {Object} jsonPayload @return {Object} jsonPayload */ /** Takes an ajax response, and returns the json payload or an error. By default this hook just returns the json payload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a `DS.InvalidError` or a `DS.AdapterError` (or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. When returning an `DS.InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. @method handleResponse @param {Number} status @param {Object} headers @param {Object} payload @return {Object | DS.AdapterError} response */ handleResponse: function (status, headers, payload) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new ember$data$lib$adapters$errors$$InvalidError(payload.errors); } var errors = this.normalizeErrorResponse(status, headers, payload); return new ember$data$lib$adapters$errors$$AdapterError(errors); }, /** Default `handleResponse` implementation uses this hook to decide if the response is a success. @method isSuccess @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isSuccess: function (status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, /** Default `handleResponse` implementation uses this hook to decide if the response is a an invalid error. @method isInvalid @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isInvalid: function (status, headers, payload) { return status === 422; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Promise} promise */ ajax: function (url, type, options) { var adapter = this; return new Ember.RSVP.Promise(function (resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function (payload, textStatus, jqXHR) { var response = undefined; if (adapter.ajaxSuccess) { Ember.deprecate("`ajaxSuccess` has been deprecated. Use `isSuccess`, `isInvalid` or `handleResponse` instead.", false, { id: "ds.adapter.ajax-success-deprecated", until: "2.0.0" }); response = adapter.ajaxSuccess(jqXHR, payload); } if (!(response instanceof ember$data$lib$adapters$errors$$AdapterError)) { response = adapter.handleResponse(jqXHR.status, ember$data$lib$adapters$rest$adapter$$parseResponseHeaders(jqXHR.getAllResponseHeaders()), response || payload); } if (response instanceof ember$data$lib$adapters$errors$$AdapterError) { Ember.run(null, reject, response); } else { Ember.run(null, resolve, response); } }; hash.error = function (jqXHR, textStatus, errorThrown) { var error = undefined; if (adapter.ajaxError) { Ember.deprecate("`ajaxError` has been deprecated. Use `isSuccess`, `isInvalid` or `handleResponse` instead.", false, { id: "ds.adapter.ajax-error-deprecated", until: "2.0.0" }); error = adapter.ajaxError(jqXHR, textStatus, errorThrown); } if (!(error instanceof Error)) { if (errorThrown instanceof Error) { error = errorThrown; } else if (textStatus === "timeout") { error = new ember$data$lib$adapters$errors$$TimeoutError(); } else if (textStatus === "abort") { error = new ember$data$lib$adapters$errors$$AbortError(); } else { error = adapter.handleResponse(jqXHR.status, ember$data$lib$adapters$rest$adapter$$parseResponseHeaders(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || errorThrown); } } Ember.run(null, reject, error); }; Ember.$.ajax(hash); }, "DS: RESTAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ 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 = ember$data$lib$adapters$rest$adapter$$get(this, "headers"); if (headers !== undefined) { hash.beforeSend = function (xhr) { ember$data$lib$adapters$rest$adapter$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(headers), function (key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** @method parseErrorResponse @private @param {String} responseText @return {Object} */ parseErrorResponse: function (responseText) { var json = responseText; try { json = Ember.$.parseJSON(responseText); } catch (e) {} return json; }, /** @method normalizeErrorResponse @private @param {Number} status @param {Object} headers @param {Object} payload @return {Object} errors payload */ 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 }]; } } }); function ember$data$lib$adapters$rest$adapter$$parseResponseHeaders(headerStr) { var headers = ember$data$lib$system$object$polyfills$$create(null); if (!headerStr) { return headers; } var headerPairs = headerStr.split("\r\n"); for (var i = 0; i < headerPairs.length; i++) { var headerPair = headerPairs[i]; // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = headerPair.indexOf(": "); if (index > 0) { var key = headerPair.substring(0, index); var val = headerPair.substring(index + 2); headers[key] = val; } } return headers; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function ember$data$lib$adapters$rest$adapter$$endsWith(string, suffix) { if (typeof String.prototype.endsWith !== "function") { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } if (Ember.platform.hasPropertyAccessors) { Ember.defineProperty(ember$data$lib$adapters$rest$adapter$$RestAdapter.prototype, "maxUrlLength", { enumerable: false, get: function () { Ember.deprecate("maxUrlLength has been deprecated (wrong casing). You should use maxURLLength instead.", false, { id: "ds.adapter.max-url-length-deprecated-case", until: "2.0.0" }); return this.maxURLLength; }, set: function (value) { Ember.deprecate("maxUrlLength has been deprecated (wrong casing). You should use maxURLLength instead.", false, { id: "ds.adapter.max-url-length-deprecated-case", until: "2.0.0" }); ember$data$lib$adapters$rest$adapter$$set(this, "maxURLLength", value); } }); } var ember$data$lib$adapters$rest$adapter$$default = ember$data$lib$adapters$rest$adapter$$RestAdapter; var ember$inflector$lib$lib$system$inflector$$capitalize = ember$lib$main$$default.String.capitalize; var ember$inflector$lib$lib$system$inflector$$BLANK_REGEX = /^\s*$/; var ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX = /([\w/-]+[_/-])([a-z\d]+$)/; var ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX = /([\w/-]+)([A-Z][a-z\d]*$)/; var ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function ember$inflector$lib$lib$system$inflector$$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 ember$inflector$lib$lib$system$inflector$$Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || ember$inflector$lib$lib$system$inflector$$makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || ember$inflector$lib$lib$system$inflector$$makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: ember$inflector$lib$lib$system$inflector$$makeDictionary(), irregularInverse: ember$inflector$lib$lib$system$inflector$$makeDictionary(), uncountable: ember$inflector$lib$lib$system$inflector$$makeDictionary() }; ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, ruleSet.uncountable); ember$inflector$lib$lib$system$inflector$$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 ember$inflector$lib$lib$system$inflector$$makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } ember$inflector$lib$lib$system$inflector$$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 = ember$inflector$lib$lib$system$inflector$$makeDictionary(); this._pCache = ember$inflector$lib$lib$system$inflector$$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(); } ember$inflector$lib$lib$system$inflector$$loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } ember$inflector$lib$lib$system$inflector$$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, isUncountable, isIrregular, rule; isBlank = !word || ember$inflector$lib$lib$system$inflector$$BLANK_REGEX.test(word); isCamelized = ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX.test(word); firstPhrase = ''; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX.exec(word) || ember$inflector$lib$lib$system$inflector$$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; } isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]); if (isIrregular) { if (irregular[lowercase]) { return isIrregular; } else { isIrregular = isCamelized ? ember$inflector$lib$lib$system$inflector$$capitalize(isIrregular) : isIrregular; return firstPhrase + isIrregular; } } 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; } }; var ember$inflector$lib$lib$system$inflector$$default = ember$inflector$lib$lib$system$inflector$$Inflector; function ember$inflector$lib$lib$system$string$$pluralize(word) { return ember$inflector$lib$lib$system$inflector$$default.inflector.pluralize(word); } function ember$inflector$lib$lib$system$string$$singularize(word) { return ember$inflector$lib$lib$system$inflector$$default.inflector.singularize(word); } var ember$inflector$lib$lib$system$inflections$$default = { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']], singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']], irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']], uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'] }; ember$inflector$lib$lib$system$inflector$$default.inflector = new ember$inflector$lib$lib$system$inflector$$default(ember$inflector$lib$lib$system$inflections$$default); var ember$inflector$lib$lib$utils$register$helper$$default = ember$inflector$lib$lib$utils$register$helper$$registerHelper; function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, helperFunction) { //earlier versions of ember with htmlbars used this ember$lib$main$$default.HTMLBars.helpers[name] = helperFunction; } function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, helperFunction) { //registerHelper has been made private as _registerHelper //this is kept here if anyone is using it ember$lib$main$$default.HTMLBars.registerHelper(name, helperFunction); } function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, helperFunction) { //latest versin of ember uses this ember$lib$main$$default.HTMLBars._registerHelper(name, helperFunction); } function ember$inflector$lib$lib$utils$register$helper$$registerHelper(name, helperFunction) { if (ember$lib$main$$default.HTMLBars) { var fn = ember$lib$main$$default.HTMLBars.makeBoundHelper(helperFunction); if (ember$lib$main$$default.HTMLBars._registerHelper) { if (ember$lib$main$$default.HTMLBars.helpers) { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, fn); } else { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, fn); } } else if (ember$lib$main$$default.HTMLBars.registerHelper) { ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, fn); } } else if (ember$lib$main$$default.Handlebars) { ember$lib$main$$default.Handlebars.helper(name, helperFunction); } } /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.HTMLBars.helpers * @method singularize * @param {String|Property} word word to singularize */ ember$inflector$lib$lib$utils$register$helper$$default('singularize', function (params) { return ember$inflector$lib$lib$system$string$$singularize(params[0]); }); /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize count myProperty}} * {{pluralize 1 "oxen"}} * {{pluralize myProperty}} * {{pluralize "ox"}} * * @for Ember.HTMLBars.helpers * @method pluralize * @param {Number|Property} [count] count of objects * @param {String|Property} word word to pluralize */ ember$inflector$lib$lib$utils$register$helper$$default('pluralize', function (params) { var count, word; if (params.length === 1) { word = params[0]; return ember$inflector$lib$lib$system$string$$pluralize(word); } else { count = params[0]; word = params[1]; if (count !== 1) { word = ember$inflector$lib$lib$system$string$$pluralize(word); } return count + ' ' + word; } }); if (ember$lib$main$$default.EXTEND_PROTOTYPES === true || ember$lib$main$$default.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function () { return ember$inflector$lib$lib$system$string$$pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function () { return ember$inflector$lib$lib$system$string$$singularize(this); }; } ember$inflector$lib$lib$system$inflector$$default.defaultRules = ember$inflector$lib$lib$system$inflections$$default; ember$lib$main$$default.Inflector = ember$inflector$lib$lib$system$inflector$$default; ember$lib$main$$default.String.pluralize = ember$inflector$lib$lib$system$string$$pluralize; ember$lib$main$$default.String.singularize = ember$inflector$lib$lib$system$string$$singularize; var ember$inflector$lib$main$$default = ember$inflector$lib$lib$system$inflector$$default; if (typeof define !== "undefined" && define.amd) { define("ember-inflector", ["exports"], function (__exports__) { __exports__["default"] = ember$inflector$lib$lib$system$inflector$$default; return ember$inflector$lib$lib$system$inflector$$default; }); } else if (typeof module !== "undefined" && module["exports"]) { module["exports"] = ember$inflector$lib$lib$system$inflector$$default; } var activemodel$adapter$lib$system$active$model$adapter$$_Ember$String = ember$lib$main$$default.String; var activemodel$adapter$lib$system$active$model$adapter$$decamelize = activemodel$adapter$lib$system$active$model$adapter$$_Ember$String.decamelize; var activemodel$adapter$lib$system$active$model$adapter$$underscore = activemodel$adapter$lib$system$active$model$adapter$$_Ember$String.underscore; /** @module ember-data */ /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active\_model\_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers, `embed :ids, embed_in_root: true` which sideloads the records. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. Unlike the DS.RESTAdapter, async relationship keys must be the singular form of the relationship name, followed by "_id" for DS.belongsTo relationships, or "_ids" for DS.hasMany relationships. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.RESTAdapter **/ var activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter = ember$data$lib$adapters$rest$adapter$$default.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} modelName @return String */ pathForType: function (modelName) { var decamelized = activemodel$adapter$lib$system$active$model$adapter$$decamelize(modelName); var underscored = activemodel$adapter$lib$system$active$model$adapter$$underscore(decamelized); return ember$inflector$lib$lib$system$string$$pluralize(underscored); }, /** The ActiveModelAdapter overrides the `handleResponse` method to format errors passed to a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param {Object} jqXHR @return error */ handleResponse: function (status, headers, payload) { if (this.isInvalid(status, headers, payload)) { var errors = ember$data$lib$adapters$errors$$errorsHashToArray(payload.errors); return new ember$data$lib$adapters$errors$$InvalidError(errors); } else { return this._super.apply(this, arguments); } } }); var activemodel$adapter$lib$system$active$model$adapter$$default = activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter; var ember$data$lib$system$serializer$$Serializer = Ember.Object.extend({ /* This is only to be used temporarily during the transition from the old serializer API to the new one. This makes the store and the built-in serializers use the new Serializer API. ## Custom Serializers If you have custom serializers you need to do the following: 1. Opt-in to the new Serializer API by setting `isNewSerializerAPI` to `true` when extending one of the built-in serializers. This indicates that the store should call `normalizeResponse` instead of `extract` and to expect a JSON-API Document back. 2. If you have a custom `extract` hooks you need to refactor it to the new `normalizeResponse` hooks and make sure it returns a JSON-API Document. 3. If you have a custom `normalize` method you need to make sure it also returns a JSON-API Document with the record in question as the primary data. @property isNewSerializerAPI */ isNewSerializerAPI: false, /** The `store` property is the application's `store` that contains all records. It's injected as a service. It can be used to push records from a non flat data structure server response. @property store @type {DS.Store} @public */ /** The `extract` method is used to deserialize the payload received from your data source into the form that Ember Data expects. @method extract @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} */ extract: 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. @method serialize @param {DS.Model} record @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. @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (typeClass, hash) { return hash; } }); var ember$data$lib$system$serializer$$default = ember$data$lib$system$serializer$$Serializer; var ember$data$lib$system$coerce$id$$default = ember$data$lib$system$coerce$id$$coerceId; // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(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 ember$data$lib$system$coerce$id$$coerceId(id) { return id == null || id === '' ? null : id + ''; } var ember$data$lib$system$normalize$model$name$$default = ember$data$lib$system$normalize$model$name$$normalizeModelName; /** All modelNames are dasherized internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method normalizeModelName @public @param {String} modelName @return {String} if the adapter can generate one, an ID @for DS */ function ember$data$lib$system$normalize$model$name$$normalizeModelName(modelName) { return Ember.String.dasherize(modelName); } var ember$data$lib$serializers$json$serializer$$get = Ember.get; var ember$data$lib$serializers$json$serializer$$isNone = Ember.isNone; var ember$data$lib$serializers$json$serializer$$map = Ember.ArrayPolyfills.map; var ember$data$lib$serializers$json$serializer$$merge = Ember.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 recommends using the JSONApiSerializer. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. `JSONSerializer` normalizes a JSON payload that looks like: ```js App.User = DS.Model.extend({ name: DS.attr(), friends: DS.hasMany('user'), house: DS.belongsTo('location'), }); ``` ```js { id: 1, name: 'Sebastian', friends: [3, 4], links: { house: '/houses/lefkada' } } ``` to JSONApi format that the Ember Data store expects. You can customize how JSONSerializer processes it's 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. 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 methods back - `normalize` - normalizeArray iterates and calls normalize for each of it's 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 JSONApi format @class JSONSerializer @namespace DS @extends DS.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. For maximum performance Ember Data recommends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS @extends DS.Serializer */ var ember$data$lib$serializers$json$serializer$$JSONSerializer = ember$data$lib$system$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"], /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {DS.Model} typeClass @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function (typeClass, data) { typeClass.eachTransformedAttribute(function applyTransform(key, typeClass) { if (!data.hasOwnProperty(key)) { return; } var transform = this.transformFor(typeClass); data[key] = transform.deserialize(data[key]); }, this); return data; }, /* The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure This method delegates to a more specific normalize method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, primaryModelClass, payload, id, requestType)` with your pre-processed data. Here's an example of using `normalizeResponse` manually: ```javascript socket.on('message', function(message) { var data = message.data; var modelClass = store.modelFor(data.modelName); var serializer = store.serializerFor(data.modelName); var json = serializer.normalizeSingleResponse(store, modelClass, data, data.id); store.push(normalized); }); ``` @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: 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); } }, /* @method normalizeFindRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /* @method normalizeQueryRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /* @method normalizeFindAllResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindAllResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /* @method normalizeFindBelongsToResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindBelongsToResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /* @method normalizeFindHasManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindHasManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /* @method normalizeFindManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /* @method normalizeQueryResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /* @method normalizeCreateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeCreateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /* @method normalizeDeleteRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeDeleteRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /* @method normalizeUpdateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeUpdateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /* @method normalizeSaveResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSaveResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /* @method normalizeSingleResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSingleResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); }, /* @method normalizeArrayResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); }, /* @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var _this = this; var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { Ember.assert("The `meta` returned from `extractMeta` has to be an object, not \"" + Ember.typeOf(meta) + "\".", Ember.typeOf(meta) === "object"); documentHash.meta = meta; } if (isSingle) { var _normalize = this.normalize(primaryModelClass, payload); var data = _normalize.data; var included = _normalize.included; documentHash.data = data; if (included) { documentHash.included = included; } } else { documentHash.data = payload.map(function (item) { var _normalize2 = _this.normalize(primaryModelClass, item); var data = _normalize2.data; var included = _normalize2.included; if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, included); } return data; }); } return documentHash; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ normalize: function(typeClass, hash) { var fields = Ember.get(typeClass, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (typeClass, hash) { if (this.get("isNewSerializerAPI")) { return ember$data$lib$serializers$json$serializer$$_newNormalize.apply(this, arguments); } if (!hash) { return hash; } this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, hash); this.applyTransforms(typeClass, hash); return hash; }, /* Returns the resource's ID. @method extractId @param {Object} modelClass @param {Object} resourceHash @return {String} */ extractId: function (modelClass, resourceHash) { var primaryKey = ember$data$lib$serializers$json$serializer$$get(this, "primaryKey"); var id = resourceHash[primaryKey]; return ember$data$lib$system$coerce$id$$default(id); }, /* Returns the resource's attributes formatted as a JSON-API "attributes object". http://jsonapi.org/format/#document-resource-object-attributes @method extractAttributes @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function (modelClass, resourceHash) { var attributeKey; var attributes = {}; modelClass.eachAttribute(function (key) { attributeKey = this.keyForAttribute(key, "deserialize"); if (resourceHash.hasOwnProperty(attributeKey)) { attributes[key] = resourceHash[attributeKey]; } }, this); return attributes; }, /* Returns a relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @return {Object} */ extractRelationship: function (relationshipModelName, relationshipHash) { if (Ember.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.typeOf(relationshipHash) === "object") { if (relationshipHash.id) { relationshipHash.id = ember$data$lib$system$coerce$id$$default(relationshipHash.id); } if (relationshipHash.type) { relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); } return relationshipHash; } return { id: ember$data$lib$system$coerce$id$$default(relationshipHash), type: relationshipModelName }; }, /* Returns the resource's relationships formatted as a JSON-API "relationships object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function (modelClass, resourceHash) { var relationships = {}; modelClass.eachRelationship(function (key, relationshipMeta) { var relationship = null; var relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, "deserialize"); if (resourceHash.hasOwnProperty(relationshipKey)) { var data = null; var relationshipHash = resourceHash[relationshipKey]; if (relationshipMeta.kind === "belongsTo") { data = this.extractRelationship(relationshipMeta.type, relationshipHash); } else if (relationshipMeta.kind === "hasMany") { data = Ember.A(relationshipHash).map(function (item) { return this.extractRelationship(relationshipMeta.type, item); }, this); } relationship = { data: data }; } var linkKey = this.keyForLink(key, relationshipMeta.kind); if (resourceHash.links && resourceHash.links.hasOwnProperty(linkKey)) { var related = resourceHash.links[linkKey]; relationship = relationship || {}; relationship.links = { related: related }; } if (relationship) { relationships[key] = relationship; } }, this); return relationships; }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function (key) { return ember$data$lib$system$normalize$model$name$$default(key); }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ normalizePayload: function(payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {Object} payload @return {Object} the normalized payload @deprecated */ normalizePayload: function (payload) { return payload; }, /** @method normalizeAttributes @private */ normalizeAttributes: function (typeClass, hash) { var payloadKey; if (this.keyForAttribute) { typeClass.eachAttribute(function (key) { payloadKey = this.keyForAttribute(key, "deserialize"); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function (typeClass, hash) { var payloadKey; if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind, "deserialize"); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function (typeClass, hash) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, "attrs"); var payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = this._getMappedKey(key); if (!hash.hasOwnProperty(payloadKey)) { continue; } if (payloadKey !== key) { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeId @private */ normalizeId: function (hash) { var primaryKey = ember$data$lib$serializers$json$serializer$$get(this, "primaryKey"); if (primaryKey === "id") { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeErrors @private */ normalizeErrors: function (typeClass, hash) { this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, hash); }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function (key) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, "attrs"); var mappedKey; 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; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function (key) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, "attrs"); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, /** When attrs.key.serialize is set to true then it takes priority over the other checks and the related attribute/relationship will be serialized @method _mustSerialize @private @param {String} key @return {boolean} true if the key must be serialized */ _mustSerialize: function (key) { var attrs = ember$data$lib$serializers$json$serializer$$get(this, "attrs"); return attrs && attrs[key] && attrs[key].serialize === true; }, /** Check if the given hasMany relationship should be serialized @method _shouldSerializeHasMany @private @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ _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 /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { var json = {}; if (options && options.includeId) { var id = snapshot.id; if (id) { json[ember$data$lib$serializers$json$serializer$$get(this, "primaryKey")] = id; } } snapshot.eachAttribute(function (key, attribute) { this.serializeAttribute(snapshot, json, key, attribute); }, this); snapshot.eachRelationship(function (key, relationship) { if (relationship.kind === "belongsTo") { this.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === "hasMany") { this.serializeHasMany(snapshot, json, relationship); } }, this); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, snapshot, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(snapshot, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { ember$data$lib$serializers$json$serializer$$merge(hash, this.serialize(snapshot, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeAttribute: function(snapshot, json, key, attributes) { json.attributes = json.attributes || {}; this._super(snapshot, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key, "serialize"); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ 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); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); } //Need to check whether the id is there for new&async records if (ember$data$lib$serializers$json$serializer$$isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; if (this._shouldSerializeHasMany(snapshot, key, relationship)) { var payloadKey; // if provided, use the mapping provided by `attrs` in // the serializer payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); } json[payloadKey] = snapshot.hasMany(key, { ids: true }); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{ polymorphic: true }` is pass as the second argument to the `DS.belongsTo` function. Example ```app/serializers/comment.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key, belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.modelName; } } }); ``` @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, type, payload, id, requestType)` with your pre-processed data. Here's an example of using `extract` manually: ```javascript socket.on('message', function(message) { var data = message.data; var typeClass = store.modelFor(message.modelName); var serializer = store.serializerFor(typeClass.modelName); var record = serializer.extract(store, typeClass, data, data.id, 'single'); store.push(message.modelName, record); }); ``` @method extract @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function (store, typeClass, payload, id, requestType) { this.extractMeta(store, typeClass.modelName, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, typeClass, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindAll: function (store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, payload, id, requestType); }, /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindQuery: function (store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, payload, id, requestType); }, /** TODO: remove this in a couple of days `extractQueryRecord` is a hook into the extract method used when a call is made to `DS.Store#queryRecord`. By default this method is an alias for [extractSingle](#method_extractSingle). @method extractQueryRecord @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} object A hash of deserialized object */ extractQueryRecord: function (store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, payload, id, requestType); }, /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindMany: function (store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, payload, id, requestType); }, /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindHasMany: function (store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, payload, id, requestType); }, /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record is new. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractCreateRecord: function (store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, payload, id, requestType); }, /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record has been updated. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractUpdateRecord: function (store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, payload, id, requestType); }, /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Model#save` and the record has been deleted. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractDeleteRecord: function (store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, payload, id, requestType); }, /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractFind: function (store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, payload, id, requestType); }, /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractFindBelongsTo: function (store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, payload, id, requestType); }, /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractSave: function (store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, payload, id, requestType); }, /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractSingle: function(store, typeClass, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, typeClass, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @param {String} requestType @return {Object} json The deserialized payload */ extractSingle: function (store, typeClass, payload, id, requestType) { if (!this.get("didDeprecateNormalizePayload")) { this.set("didDeprecateNormalizePayload", true); Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$JSONSerializer.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); } var normalizedPayload = this.normalizePayload(payload); return this.normalize(typeClass, normalizedPayload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractArray: function(store, typeClass, payload) { return payload.map(function(json) { return this.extractSingle(store, typeClass, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {DS.Model} typeClass @param {Object} arrayPayload @param {(String|Number)} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractArray: function (store, typeClass, arrayPayload, id, requestType) { if (!this.get("didDeprecateNormalizePayload")) { this.set("didDeprecateNormalizePayload", true); Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$JSONSerializer.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); } var normalizedPayload = this.normalizePayload(arrayPayload); var serializer = this; return ember$data$lib$serializers$json$serializer$$map.call(normalizedPayload, function (singlePayload) { return serializer.normalize(typeClass, singlePayload); }); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractMeta: function(store, typeClass, payload) { if (payload && payload._pagination) { store.setMetadataFor(typeClass, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload */ extractMeta: function (store, typeClass, payload) { if (this.get("isNewSerializerAPI")) { return ember$data$lib$serializers$json$serializer$$_newExtractMeta.apply(this, arguments); } if (payload && payload.meta) { store._setMetadataFor(typeClass, payload.meta); delete payload.meta; } }, /** `extractErrors` is used to extract model errors when a call is made to `DS.Model#save` which fails with an `InvalidError`. By default Ember Data expects error information to be located on the `errors` property of the payload object. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractErrors: function(store, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(typeClass, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @return {Object} json The deserialized errors */ extractErrors: function (store, typeClass, payload, id) { if (payload && typeof payload === "object" && payload.errors) { payload = ember$data$lib$adapters$errors$$errorsArrayToHash(payload.errors); this.normalizeErrors(typeClass, payload); } return payload; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship, method) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return key; }, /** `keyForLink` can be used to define a custom key when deserializing link properties. @method keyForLink @param {String} key @param {String} kind `belongsTo` or `hasMany` @return {String} normalized key */ keyForLink: function (key, kind) { return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function (attributeType, skipAssertion) { var transform = this.container.lookup("transform:" + attributeType); Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); /* @method _newNormalize @param {DS.Model} modelClass @param {Object} resourceHash @return {Object} @private */ function ember$data$lib$serializers$json$serializer$$_newNormalize(modelClass, resourceHash) { var data = null; if (resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); 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 }; } /* @method _newExtractMeta @param {DS.Store} store @param {DS.Model} modelClass @param {Object} payload @return {Object} @private */ function ember$data$lib$serializers$json$serializer$$_newExtractMeta(store, modelClass, payload) { if (payload && payload.hasOwnProperty("meta")) { var meta = payload.meta; delete payload.meta; return meta; } } var ember$data$lib$serializers$json$serializer$$default = ember$data$lib$serializers$json$serializer$$JSONSerializer; var ember$data$lib$system$promise$proxies$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$promise$proxies$$get = Ember.get; /** 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 var 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 ember$data$lib$system$promise$proxies$$PromiseArray = Ember.ArrayProxy.extend(Ember.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 var 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 ember$data$lib$system$promise$proxies$$PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); var ember$data$lib$system$promise$proxies$$promiseObject = function (promise, label) { return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label) }); }; var ember$data$lib$system$promise$proxies$$promiseArray = function (promise, label) { return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: ember$data$lib$system$promise$proxies$$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 ember$data$lib$system$promise$proxies$$proxyToContent(method) { return function () { var content = ember$data$lib$system$promise$proxies$$get(this, 'content'); return content[method].apply(content, arguments); }; } var ember$data$lib$system$promise$proxies$$PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseArray.extend({ reload: function () { //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships Ember.assert('You are trying to reload an async manyArray before it has been created', ember$data$lib$system$promise$proxies$$get(this, 'content')); return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ promise: ember$data$lib$system$promise$proxies$$get(this, 'content').reload() }); }, createRecord: ember$data$lib$system$promise$proxies$$proxyToContent('createRecord'), on: ember$data$lib$system$promise$proxies$$proxyToContent('on'), one: ember$data$lib$system$promise$proxies$$proxyToContent('one'), trigger: ember$data$lib$system$promise$proxies$$proxyToContent('trigger'), off: ember$data$lib$system$promise$proxies$$proxyToContent('off'), has: ember$data$lib$system$promise$proxies$$proxyToContent('has') }); var ember$data$lib$system$promise$proxies$$promiseManyArray = function (promise, label) { return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label) }); }; var ember$data$lib$system$model$errors$$get = Ember.get; var ember$data$lib$system$model$errors$$set = Ember.set; var ember$data$lib$system$model$errors$$isEmpty = Ember.isEmpty; var ember$data$lib$system$model$errors$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$model$errors$$makeArray = Ember.makeArray; var ember$data$lib$system$model$errors$$default = Ember.ArrayProxy.extend(Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function (target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.computed(function () { return ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function () { return Ember.A(); } }); }), /** Returns errors for a given attribute ```javascript var 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 ember$data$lib$system$model$errors$$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.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function () { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function (attribute) { var errors = this.errorsFor(attribute); if (ember$data$lib$system$model$errors$$isEmpty(errors)) { return null; } return errors; }, /** Total number of errors. @property length @type {Number} @readOnly */ /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.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 */ add: function (attribute, messages) { var wasEmpty = ember$data$lib$system$model$errors$$get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); this.addObjects(messages); ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); this.notifyPropertyChange(attribute); if (wasEmpty && !ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function (attribute, messages) { var errors = this.errorsFor(attribute); return ember$data$lib$system$model$errors$$map.call(ember$data$lib$system$model$errors$$makeArray(messages), function (message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** 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 */ remove: function (attribute) { if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; } var content = this.rejectBy('attribute', attribute); ember$data$lib$system$model$errors$$set(this, 'content', content); ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName')["delete"](attribute); this.notifyPropertyChange(attribute); if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** 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 */ clear: function () { if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) { return; } var errorsByAttributeName = ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName'); var attributes = Ember.A(); errorsByAttributeName.forEach(function (_, attribute) { attributes.push(attribute); }); errorsByAttributeName.clear(); attributes.forEach(function (attribute) { this.notifyPropertyChange(attribute); }, this); this._super(); this.trigger('becameValid'); }, /** 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 !ember$data$lib$system$model$errors$$isEmpty(this.errorsFor(attribute)); } }); var ember$new$computed$lib$utils$can$use$new$syntax$$supportsSetterGetter; try { ember$lib$main$$default.computed({ set: function () {}, get: function () {} }); ember$new$computed$lib$utils$can$use$new$syntax$$supportsSetterGetter = true; } catch (e) { ember$new$computed$lib$utils$can$use$new$syntax$$supportsSetterGetter = false; } var ember$new$computed$lib$utils$can$use$new$syntax$$default = ember$new$computed$lib$utils$can$use$new$syntax$$supportsSetterGetter; var ember$new$computed$lib$main$$default = ember$new$computed$lib$main$$newComputed; var ember$new$computed$lib$main$$computed = ember$lib$main$$default.computed; function ember$new$computed$lib$main$$newComputed() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || ember$new$computed$lib$utils$can$use$new$syntax$$default) { return ember$new$computed$lib$main$$computed.apply(undefined, arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function (key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function (key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return ember$new$computed$lib$main$$computed.apply(undefined, polyfillArguments); } var ember$new$computed$lib$main$$getKeys = Object.keys || ember$lib$main$$default.keys; var ember$new$computed$lib$main$$computedKeys = ember$new$computed$lib$main$$getKeys(ember$new$computed$lib$main$$computed); for (var ember$new$computed$lib$main$$i = 0, ember$new$computed$lib$main$$l = ember$new$computed$lib$main$$computedKeys.length; ember$new$computed$lib$main$$i < ember$new$computed$lib$main$$l; ember$new$computed$lib$main$$i++) { ember$new$computed$lib$main$$newComputed[ember$new$computed$lib$main$$computedKeys[ember$new$computed$lib$main$$i]] = ember$new$computed$lib$main$$computed[ember$new$computed$lib$main$$computedKeys[ember$new$computed$lib$main$$i]]; } var ember$data$lib$system$model$model$$errorDeprecationShown = false; /** @module ember-data */ var ember$data$lib$system$model$model$$get = Ember.get; var ember$data$lib$system$model$model$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$model$model$$indexOf = Ember.ArrayPolyfills.indexOf; var ember$data$lib$system$model$model$$merge = Ember.merge; var ember$data$lib$system$model$model$$copy = Ember.copy; function ember$data$lib$system$model$model$$intersection(array1, array2) { var result = []; ember$data$lib$system$model$model$$forEach.call(array1, function (element) { if (ember$data$lib$system$model$model$$indexOf.call(array2, element) >= 0) { result.push(element); } }); return result; } var ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS = ["currentState", "data", "store"]; var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed("currentState", function (key) { return ember$data$lib$system$model$model$$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 ember$data$lib$system$model$model$$Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, _internalModel: null, store: null, /** 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: ember$data$lib$system$model$model$$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: ember$data$lib$system$model$model$$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 var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: ember$data$lib$system$model$model$$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 var record = store.createRecord('model'); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.get('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly @deprecated */ isDirty: Ember.computed("currentState.isDirty", function () { Ember.deprecate("DS.Model#isDirty has been deprecated please use hasDirtyAttributes instead", false, { id: "ds.model.is-dirty-deprecated", until: "2.0.0" }); return this.get("currentState.isDirty"); }), /** @property error @type {Boolean} @deprecated */ error: ember$new$computed$lib$main$$default("adapterError", { get: function () { if (!ember$data$lib$system$model$model$$errorDeprecationShown) { Ember.deprecate("DS.Model#error has been deprecated please use adapterError instead"); ember$data$lib$system$model$model$$errorDeprecationShown = true; } return Ember.get(this, "adapterError"); } }), /** 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 var record = store.createRecord('model'); record.get('hasDirtyAttributes'); // true store.find('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: Ember.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 var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: ember$data$lib$system$model$model$$retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been 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. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var 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('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: ember$data$lib$system$model$model$$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 var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: ember$data$lib$system$model$model$$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: ember$data$lib$system$model$model$$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 var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: ember$data$lib$system$model$model$$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 form 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 var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ /** 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: Ember.computed(function () { var errors = ember$data$lib$system$model$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, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this.store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ 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: Ember.K, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed.readOnly("_internalModel._data"), //TODO Do we want to deprecate these? /** @method send @private @param {String} name @param {Object} context */ send: function (name, context) { return this._internalModel.send(name, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function (name) { return this._internalModel.transitionTo(name); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollbackAttributes()` after a delete it was made. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollbackAttributes(); } } }); ``` @method deleteRecord */ deleteRecord: function () { this._internalModel.deleteRecord(); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function (options) { this.deleteRecord(); return this.save(options); }, /** @method unloadRecord @private */ unloadRecord: function () { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, /** @method _notifyProperties @private */ _notifyProperties: function (keys) { Ember.beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } Ember.endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```app/models/mascot.js import DS from 'ember-data'; export default DS.Model.extend({ name: attr('string') }); ``` ```javascript var mascot = store.createRecord('mascot'); mascot.changedAttributes(); // {} mascot.set('name', 'Tomster'); mascot.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function () { var oldData = ember$data$lib$system$model$model$$get(this._internalModel, "_data"); var currentData = ember$data$lib$system$model$model$$get(this._internalModel, "_attributes"); var inFlightData = ember$data$lib$system$model$model$$get(this._internalModel, "_inFlightAttributes"); var newData = ember$data$lib$system$model$model$$merge(ember$data$lib$system$model$model$$copy(inFlightData), currentData); var diffData = ember$data$lib$system$object$polyfills$$create(null); var newDataKeys = ember$data$lib$system$object$polyfills$$keysFunc(newData); for (var i = 0, _length = newDataKeys.length; i < _length; i++) { var key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; }, //TODO discuss with tomhuda about events/hooks //Bring back as hooks? /** @method adapterWillCommit @private adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, */ /** If the model `isDirty` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback @deprecated Use `rollbackAttributes()` instead */ rollback: function () { Ember.deprecate("Using model.rollback() has been deprecated. Use model.rollbackAttributes() to discard any unsaved changes to a model.", false, { id: "ds.model.rollback-deprecated", until: "2.0.0" }); this.rollbackAttributes(); }, /** If the model `isDirty` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @method rollbackAttributes */ rollbackAttributes: function () { this._internalModel.rollbackAttributes(); }, /* @method _createSnapshot @private */ _createSnapshot: function () { return this._internalModel.createSnapshot(); }, toStringExtension: function () { return ember$data$lib$system$model$model$$get(this, "id"); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` @method save @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function (options) { var model = this; return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: this._internalModel.save(options).then(function () { return model; }) }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```app/routes/model/view.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function () { var model = this; return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: this._internalModel.reload().then(function () { return model; }) }); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function (name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } Ember.tryInvoke(this, name, args); this._super.apply(this, arguments); }, willDestroy: function () { //TODO Move! this._internalModel.clearRelationships(); this._internalModel.recordObjectWillDestroy(); this._super.apply(this, arguments); //TODO should we set internalModel to null here? }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function (props) { var constructor = this.constructor; Ember.assert("`" + ember$data$lib$system$model$model$$intersection(ember$data$lib$system$object$polyfills$$keysFunc(props), ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS)[0] + "` is a reserved property name on DS.Model objects. Please choose a different property name for " + constructor.toString(), !ember$data$lib$system$model$model$$intersection(ember$data$lib$system$object$polyfills$$keysFunc(props), ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS)[0]); }, attr: function () { Ember.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 () { Ember.assert("The `belongsTo` 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); }, hasMany: function () { Ember.assert("The `hasMany` 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); } }); ember$data$lib$system$model$model$$Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: ember$data$lib$system$model$model$$Model.create, /** 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 */ create: function () { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); }, /** Represents the model's class name as a string. This can be used to look up the model 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 var PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly */ modelName: null }); var ember$data$lib$system$model$model$$default = ember$data$lib$system$model$model$$Model; var ember$data$lib$system$store$serializer$response$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$store$serializer$response$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$store$serializer$response$$get = Ember.get; /** This is a helper method that always returns a JSON-API Document. If the current serializer has `isNewSerializerAPI` set to `true` this helper calls `normalizeResponse` instead of `extract`. All the built-in serializers get `isNewSerializerAPI` set to `true` automatically if the feature flag is enabled. @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 ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { if (ember$data$lib$system$store$serializer$response$$get(serializer, 'isNewSerializerAPI')) { var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); // TODO: Remove after metadata refactor if (normalizedResponse.meta) { store._setMetadataFor(modelClass.modelName, normalizedResponse.meta); } return normalizedResponse; } else { Ember.deprecate('Your custom serializer uses the old version of the Serializer API, with `extract` hooks. Please upgrade your serializers to the new Serializer API using `normalizeResponse` hooks instead.', false, { id: 'ds.serializer.extract-hooks-deprecated', until: '2.0.0' }); var serializerPayload = serializer.extract(store, modelClass, payload, id, requestType); return ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayload(modelClass, serializerPayload); } } /** Convert the payload from `serializer.extract` to a JSON-API Document. @method _normalizeSerializerPayload @private @param {subclass of DS.Model} modelClass @param {Object} payload @return {Object} JSON-API Document */ function ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayload(modelClass, payload) { var data = null; if (payload) { if (Ember.typeOf(payload) === 'array') { data = ember$data$lib$system$store$serializer$response$$map.call(payload, function (payload) { return ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayloadItem(modelClass, payload); }); } else { data = ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayloadItem(modelClass, payload); } } return { data: data }; } /** Convert the payload representing a single record from `serializer.extract` to a JSON-API Resource Object. @method _normalizeSerializerPayloadItem @private @param {subclass of DS.Model} modelClass @param {Object} payload @return {Object} JSON-API Resource Object */ function ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayloadItem(modelClass, itemPayload) { var item = {}; item.id = '' + itemPayload.id; item.type = modelClass.modelName; item.attributes = {}; item.relationships = {}; modelClass.eachAttribute(function (name) { if (itemPayload.hasOwnProperty(name)) { item.attributes[name] = itemPayload[name]; } }); modelClass.eachRelationship(function (key, relationshipMeta) { var relationship, value; if (itemPayload.hasOwnProperty(key)) { var relationshipData; (function () { relationship = {}; value = itemPayload[key]; var normalizeRelationshipData = function (value, relationshipMeta) { if (Ember.isNone(value)) { return null; } //Temporary support for https://github.com/emberjs/data/issues/3271 if (value instanceof ember$data$lib$system$model$model$$default) { value = { id: value.id, type: value.constructor.modelName }; } if (Ember.typeOf(value) === 'object') { Ember.assert('Ember Data expected a number or string to represent the record(s) in the `' + key + '` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `' + key + '` property in your serializer\'s attrs object.', value.type); if (value.id) { value.id = '' + value.id; } return value; } Ember.assert('A ' + relationshipMeta.parentType + ' record was pushed into the store with the value of ' + key + ' being ' + Ember.inspect(value) + ', but ' + key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Ember.isArray(value)); return { id: '' + value, type: relationshipMeta.type }; }; if (relationshipMeta.kind === 'belongsTo') { relationship.data = normalizeRelationshipData(value, relationshipMeta); //handle the belongsTo polymorphic case, where { post:1, postType: 'video' } if (relationshipMeta.options && relationshipMeta.options.polymorphic && itemPayload[key + 'Type']) { relationship.data.type = itemPayload[key + 'Type']; } } else if (relationshipMeta.kind === 'hasMany') { //|| [] because the hasMany could be === null Ember.assert('A ' + relationshipMeta.parentType + ' record was pushed into the store with the value of ' + key + ' being \'' + Ember.inspect(value) + '\', but ' + key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Ember.isArray(value) || value === null); relationshipData = Ember.A(value || []); relationship.data = ember$data$lib$system$store$serializer$response$$map.call(relationshipData, function (item) { return normalizeRelationshipData(item, relationshipMeta); }); } })(); } if (itemPayload.links && itemPayload.links.hasOwnProperty(key)) { relationship = relationship || {}; value = itemPayload.links[key]; relationship.links = { related: value }; } if (relationship) { relationship.meta = ember$data$lib$system$store$serializer$response$$get(itemPayload, 'meta.' + key); item.relationships[key] = relationship; } }); return item; } /** Push a JSON-API Document to the store. This will push both primary data located in `data` and secondary data located in `included` (if present). @method pushPayload @param {DS.Store} store @param {Object} payload @return {DS.Model|Array} one or multiple records from `data` */ function ember$data$lib$system$store$serializer$response$$pushPayload(store, payload) { var result = ember$data$lib$system$store$serializer$response$$pushPayloadData(store, payload); ember$data$lib$system$store$serializer$response$$pushPayloadIncluded(store, payload); return result; } /** Push the primary data of a JSON-API Document to the store. This method only pushes the primary data located in `data`. @method pushPayloadData @param {DS.Store} store @param {Object} payload @return {DS.Model|Array} one or multiple records from `data` */ function ember$data$lib$system$store$serializer$response$$pushPayloadData(store, payload) { var result; if (payload && payload.data) { if (Ember.isArray(payload.data)) { result = ember$data$lib$system$store$serializer$response$$map.call(payload.data, function (item) { return ember$data$lib$system$store$serializer$response$$_pushResourceObject(store, item); }); } else { result = ember$data$lib$system$store$serializer$response$$_pushResourceObject(store, payload.data); } } return result; } /** Push the secondary data of a JSON-API Document to the store. This method only pushes the secondary data located in `included`. @method pushPayloadIncluded @param {DS.Store} store @param {Object} payload @return {Array} an array containing zero or more records from `included` */ function ember$data$lib$system$store$serializer$response$$pushPayloadIncluded(store, payload) { var result; if (payload && payload.included && Ember.isArray(payload.included)) { result = ember$data$lib$system$store$serializer$response$$map.call(payload.included, function (item) { return ember$data$lib$system$store$serializer$response$$_pushResourceObject(store, item); }); } return result; } /** Push a single JSON-API Resource Object to the store. @method _pushResourceObject @private @param {Object} resourceObject @return {DS.Model} a record */ function ember$data$lib$system$store$serializer$response$$_pushResourceObject(store, resourceObject) { return store.push({ data: resourceObject }); } /** This method converts a JSON-API Resource Object to a format that DS.Store understands. TODO: This method works as an interim until DS.Store understands JSON-API. @method convertResourceObject @param {Object} payload @return {Object} an object formatted the way DS.Store understands */ function ember$data$lib$system$store$serializer$response$$convertResourceObject(payload) { if (!payload) { return payload; } var data = { id: payload.id, type: payload.type, links: {} }; if (payload.attributes) { var attributeKeys = ember$data$lib$system$object$polyfills$$keysFunc(payload.attributes); ember$data$lib$system$store$serializer$response$$forEach.call(attributeKeys, function (key) { var attribute = payload.attributes[key]; data[key] = attribute; }); } if (payload.relationships) { var relationshipKeys = ember$data$lib$system$object$polyfills$$keysFunc(payload.relationships); ember$data$lib$system$store$serializer$response$$forEach.call(relationshipKeys, function (key) { var relationship = payload.relationships[key]; if (relationship.hasOwnProperty('data')) { data[key] = relationship.data; } else if (relationship.links && relationship.links.related) { data.links[key] = relationship.links.related; } }); } return data; } var ember$data$lib$serializers$rest$serializer$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$serializers$rest$serializer$$map = Ember.ArrayPolyfills.map; var ember$data$lib$serializers$rest$serializer$$camelize = Ember.String.camelize; var ember$data$lib$serializers$rest$serializer$$get = Ember.get; /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. 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 Parse, 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: function(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 ember$data$lib$serializers$rest$serializer$$RESTSerializer = ember$data$lib$serializers$json$serializer$$default.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined @deprecated */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {DS.Model} typeClass @param {Object} hash @param {String} prop @return {Object} */ normalize: function (typeClass, hash, prop) { if (this.get("isNewSerializerAPI")) { ember$data$lib$serializers$rest$serializer$$_newNormalize.apply(this, arguments); return this._super.apply(this, arguments); } this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, hash); if (this.normalizeHash && this.normalizeHash[prop]) { Ember.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: "2.0.0" }); this.normalizeHash[prop](hash); } this.applyTransforms(typeClass, hash); return hash; }, /* Normalizes an array of resource payloads and returns a JSON-API Document with primary data and, if any, included data as `{ data, included }`. @method normalizeArray @param {DS.Store} store @param {String} modelName @param {Object} arrayHash @param {String} prop @return {Object} */ normalizeArray: function (store, modelName, arrayHash, prop) { var documentHash = { data: [], included: [] }; var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); Ember.assert(this.toString() + " has opted into the new serializer API and expects the " + serializer.toString() + " it collaborates with to also support the new serializer API by setting its `isNewSerializerAPI` property to true.", ember$data$lib$serializers$rest$serializer$$get(serializer, "isNewSerializerAPI")); /*jshint loopfunc:true*/ ember$data$lib$serializers$rest$serializer$$forEach.call(arrayHash, function (hash) { var _serializer$normalize = serializer.normalize(modelClass, hash, prop); var data = _serializer$normalize.data; var included = _serializer$normalize.included; documentHash.data.push(data); if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, included); } }, this); return documentHash; }, /* @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { Ember.assert("The `meta` returned from `extractMeta` has to be an object, not \"" + Ember.typeOf(meta) + "\".", Ember.typeOf(meta) === "object"); documentHash.meta = meta; } var keys = ember$data$lib$system$object$polyfills$$keysFunc(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)) { Ember.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; } /* Support primary data as an object instead of an array. Example ``` { user: { id: 1, title: 'Tom', manager: 3 } } ``` */ if (isPrimary && Ember.typeOf(value) !== "array") { var _normalize = this.normalize(primaryModelClass, value, prop); var _data = _normalize.data; var _included = _normalize.included; documentHash.data = _data; if (_included) { var _documentHash$included2; (_documentHash$included2 = documentHash.included).push.apply(_documentHash$included2, _included); } continue; } var _normalizeArray = this.normalizeArray(store, typeName, value, prop); var data = _normalizeArray.data; var included = _normalizeArray.included; if (included) { var _documentHash$included3; (_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, included); } if (isSingle) { /*jshint loopfunc:true*/ ember$data$lib$serializers$rest$serializer$$forEach.call(data, 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 && ember$data$lib$system$coerce$id$$default(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$included4; (_documentHash$included4 = documentHash.included).push.apply(_documentHash$included4, data); } } } } return documentHash; }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, typeClass, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, typeClass, payload, id); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {DS.Model} primaryTypeClass @param {Object} rawPayload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function (store, primaryTypeClass, rawPayload, recordId) { Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$default.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); var payload = this.normalizePayload(rawPayload); var primaryRecord; for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { Ember.warn(this.warnMessageNoModelForKey(prop, modelName), false, { id: "ds.serializer.model-for-key-missing" }); continue; } var isPrimary = this.isPrimaryType(store, modelName, primaryTypeClass); var value = payload[prop]; if (value === null) { continue; } // legacy support for singular resources if (isPrimary && Ember.typeOf(value) !== "array") { primaryRecord = this.normalize(primaryTypeClass, value, prop); continue; } /*jshint loopfunc:true*/ ember$data$lib$serializers$rest$serializer$$forEach.call(value, function (hash) { var typeName = this.modelNameFromPayloadKey(prop); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type.modelName); Ember.assert(this.toString() + " is using the " + (ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") ? "new" : "old") + " serializer API and expects " + typeSerializer.toString() + " it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.", ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") === ember$data$lib$serializers$rest$serializer$$get(typeSerializer, "isNewSerializerAPI")); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord; var isUpdatedRecord = isPrimary && ember$data$lib$system$coerce$id$$default(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(modelName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi", "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; }); payload = { comments: comments, posts: posts }; return this._super(store, type, payload); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {DS.Model} primaryTypeClass @param {Object} rawPayload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function (store, primaryTypeClass, rawPayload) { Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$default.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); var payload = this.normalizePayload(rawPayload); var primaryArray; for (var prop in payload) { var modelName = prop; var forcedSecondary = false; if (prop.charAt(0) === "_") { forcedSecondary = true; modelName = prop.substr(1); } var typeName = this.modelNameFromPayloadKey(modelName); if (!store.modelFactoryFor(typeName)) { Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false, { id: "ds.serializer.model-for-key-missing" }); continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type.modelName); Ember.assert(this.toString() + " is using the " + (ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") ? "new" : "old") + " serializer API and expects " + typeSerializer.toString() + " it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.", ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") === ember$data$lib$serializers$rest$serializer$$get(typeSerializer, "isNewSerializerAPI")); var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryTypeClass); /*jshint loopfunc:true*/ var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(payload[prop], function (hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, isPrimaryType: function (store, typeName, primaryTypeClass) { var typeClass = store.modelFor(typeName); return typeClass.modelName === primaryTypeClass.modelName; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} rawPayload */ pushPayload: function (store, rawPayload) { if (this.get("isNewSerializerAPI")) { ember$data$lib$serializers$rest$serializer$$_newPushPayload.apply(this, arguments); return; } Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$default.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); var payload = this.normalizePayload(rawPayload); for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { Ember.warn(this.warnMessageNoModelForKey(prop, modelName), false, { id: "ds.serializer.model-for-key-missing" }); continue; } var typeClass = store.modelFor(modelName); var typeSerializer = store.serializerFor(modelName); Ember.assert(this.toString() + " is using the " + (ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") ? "new" : "old") + " serializer API and expects " + typeSerializer.toString() + " it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.", ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") === ember$data$lib$serializers$rest$serializer$$get(typeSerializer, "isNewSerializerAPI")); /*jshint loopfunc:true*/ var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(Ember.makeArray(payload[prop]), function (hash) { return typeSerializer.normalize(typeClass, hash, prop); }, this); store.pushMany(modelName, normalizedArray); } }, /** This method is used to convert each JSON root key in the payload into a modelName that it can use to look up the appropriate model for that part of the payload. For example, your server may send a model name that does not correspond with the name of the model in your app. Let's take a look at an example model, and an example payload: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ }); ``` ```javascript { "blog/post": { "id": "1 } } ``` Ember Data is going to normalize the payload's root key for the modelName. As a result, it will try to look up the "blog/post" model. Since we don't have a model called "blog/post" (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error because it cannot find the "blog/post" model. Since we want to remove this namespace, we can define a serializer for the application that will remove "blog/" from the payload key whenver it's encountered by Ember Data: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ modelNameFromPayloadKey: function(payloadKey) { if (payloadKey === 'blog/post') { return this._super(payloadKey.replace('blog/', '')); } else { return this._super(payloadKey); } } }); ``` After refreshing, Ember Data will appropriately look up the "post" model. By default the modelName for a model is its name in dasherized form. This means that a payload key like "blogPost" would be normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadKey` for this purpose. @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function (key) { return ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = this._super(snapshot, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends the modelName of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); hash[normalizedRootKey] = this.serialize(snapshot, options); }, /** You can use `payloadKeyFromModelName` to override the root key for an outgoing request. By default, the RESTSerializer returns a camelized version of the model's name. For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer will send it to the server with `tacoParty` as the root key in the JSON payload: ```js { "tacoParty": { "id": "1", "location": "Matthew Beale's House" } } ``` For example, your server may expect dasherized root objects: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.dasherize(modelName); } }); ``` Given a `TacoParty' model, calling `save` on a tacoModel would produce an outgoing request like: ```js { "taco-party": { "id": "1", "location": "Matthew Beale's House" } } ``` @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function (modelName) { return ember$data$lib$serializers$rest$serializer$$camelize(modelName); }, /** Deprecated. Use modelNameFromPayloadKey instead @method typeForRoot @param {String} modelName @return {String} @deprecated */ typeForRoot: function (modelName) { Ember.deprecate("typeForRoot is deprecated. Use modelNameFromPayloadKey instead.", false, { id: "ds.serializer.type-for-root-deprecated", until: "2.0.0" }); return this.modelNameFromPayloadKey(modelName); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function (snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "Type"] = null; } else { json[key + "Type"] = Ember.String.camelize(belongsTo.modelName); } } }); Ember.runInDebug(function () { ember$data$lib$serializers$rest$serializer$$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 + "\"))"; } }); }); var ember$data$lib$serializers$rest$serializer$$default = ember$data$lib$serializers$rest$serializer$$RESTSerializer; /* @method _newNormalize @param {DS.Model} modelClass @param {Object} resourceHash @param {String} prop @return {Object} @private */ function ember$data$lib$serializers$rest$serializer$$_newNormalize(modelClass, resourceHash, prop) { if (this.normalizeHash && this.normalizeHash[prop]) { Ember.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: "2.0.0" }); this.normalizeHash[prop](resourceHash); } } /* @method _newPushPayload @param {DS.Store} store @param {Object} rawPayload */ function ember$data$lib$serializers$rest$serializer$$_newPushPayload(store, rawPayload) { var documentHash = { data: [], included: [] }; Ember.deprecate("`serializer.normalizePayload` has been deprecated. Please use `serializer.normalizeResponse` with the new Serializer API to modify the payload.", this.normalizePayload === ember$data$lib$serializers$json$serializer$$default.prototype.normalizePayload, { id: "ds.serializer.normalize-payload-deprecated", until: "2.0.0" }); var payload = this.normalizePayload(rawPayload); for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { Ember.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.assert(this.toString() + " is using the " + (ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") ? "new" : "old") + " serializer API and expects " + typeSerializer.toString() + " it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.", ember$data$lib$serializers$rest$serializer$$get(this, "isNewSerializerAPI") === ember$data$lib$serializers$rest$serializer$$get(typeSerializer, "isNewSerializerAPI")); /*jshint loopfunc:true*/ ember$data$lib$serializers$rest$serializer$$forEach.call(Ember.makeArray(payload[prop]), function (hash) { var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop); var data = _typeSerializer$normalize.data; var included = _typeSerializer$normalize.included; documentHash.data.push(data); if (included) { var _documentHash$included5; (_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, included); } }, this); } ember$data$lib$system$store$serializer$response$$pushPayload(store, documentHash); } /** @module ember-data */ var activemodel$adapter$lib$system$active$model$serializer$$_Ember$String = ember$lib$main$$default.String; var activemodel$adapter$lib$system$active$model$serializer$$singularize = activemodel$adapter$lib$system$active$model$serializer$$_Ember$String.singularize; var activemodel$adapter$lib$system$active$model$serializer$$classify = activemodel$adapter$lib$system$active$model$serializer$$_Ember$String.classify; var activemodel$adapter$lib$system$active$model$serializer$$decamelize = activemodel$adapter$lib$system$active$model$serializer$$_Ember$String.decamelize; var activemodel$adapter$lib$system$active$model$serializer$$camelize = activemodel$adapter$lib$system$active$model$serializer$$_Ember$String.camelize; var activemodel$adapter$lib$system$active$model$serializer$$underscore = activemodel$adapter$lib$system$active$model$serializer$$_Ember$String.underscore; /** The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active\_model\_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers, `embed :ids, embed_in_root: true` which sideloads the records. This serializer extends the DS.RESTSerializer by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelSerializer expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelSerializer @namespace DS @extends DS.RESTSerializer */ var activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer = ember$data$lib$serializers$rest$serializer$$default.extend({ // SERIALIZE /** Converts camelCased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @return String */ keyForAttribute: function (attr) { return activemodel$adapter$lib$system$active$model$serializer$$decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} relationshipModelName @param {String} kind @return String */ keyForRelationship: function (relationshipModelName, kind) { var key = activemodel$adapter$lib$system$active$model$serializer$$decamelize(relationshipModelName); if (kind === 'belongsTo') { return key + '_id'; } else if (kind === 'hasMany') { return activemodel$adapter$lib$system$active$model$serializer$$singularize(key) + '_ids'; } else { return key; } }, /** `keyForLink` can be used to define a custom key when deserializing link properties. The `ActiveModelSerializer` camelizes link keys by default. @method keyForLink @param {String} key @param {String} kind `belongsTo` or `hasMany` @return {String} normalized key */ keyForLink: function (key, relationshipKind) { return activemodel$adapter$lib$system$active$model$serializer$$camelize(key); }, /* Does not serialize hasMany relationships by default. */ serializeHasMany: ember$lib$main$$default.K, /** Underscores the JSON root keys when serializing. @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function (modelName) { return activemodel$adapter$lib$system$active$model$serializer$$underscore(activemodel$adapter$lib$system$active$model$serializer$$decamelize(modelName)); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function (snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var jsonKey = activemodel$adapter$lib$system$active$model$serializer$$underscore(key + '_type'); if (ember$lib$main$$default.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = activemodel$adapter$lib$system$active$model$serializer$$classify(belongsTo.modelName).replace('/', '::'); } }, // EXTRACT /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} typeClass @param {Object} hash @param {String} prop @return Object */ normalize: function (typeClass, hash, prop) { this.normalizeLinks(hash); return this._super(typeClass, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data */ normalizeLinks: function (data) { if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = activemodel$adapter$lib$system$active$model$serializer$$camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @param {Subclass of DS.Model} typeClass @method normalizeRelationships @private */ normalizeRelationships: function (typeClass, hash) { if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { var payloadKey, payload; if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key, 'deserialize'); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.modelNameFromPayloadKey(payload.type); } else if (payload && relationship.kind === 'hasMany') { for (var i = 0, len = payload.length; i < len; i++) { var single = payload[i]; single.type = this.modelNameFromPayloadKey(single.type); } } } else { payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize'); if (!hash.hasOwnProperty(payloadKey)) { return; } payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } }, extractRelationships: function (modelClass, resourceHash) { modelClass.eachRelationship(function (key, relationshipMeta) { var relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); // prefer the format the AMS gem expects, e.g.: // relationship: {id: id, type: type} if (relationshipMeta.options.polymorphic) { activemodel$adapter$lib$system$active$model$serializer$$extractPolymorphicRelationships(key, relationshipMeta, resourceHash, relationshipKey); } // If the preferred format is not found, use {relationship_name_id, relationship_name_type} if (resourceHash.hasOwnProperty(relationshipKey) && typeof resourceHash[relationshipKey] !== 'object') { var polymorphicTypeKey = this.keyForRelationship(key) + '_type'; if (resourceHash[polymorphicTypeKey] && relationshipMeta.options.polymorphic) { var id = resourceHash[relationshipKey]; var type = resourceHash[polymorphicTypeKey]; delete resourceHash[polymorphicTypeKey]; delete resourceHash[relationshipKey]; resourceHash[relationshipKey] = { id: id, type: type }; } } }, this); return this._super.apply(this, arguments); }, modelNameFromPayloadKey: function (key) { var convertedFromRubyModule = activemodel$adapter$lib$system$active$model$serializer$$singularize(key.replace('::', '/')); return ember$data$lib$system$normalize$model$name$$default(convertedFromRubyModule); } }); function activemodel$adapter$lib$system$active$model$serializer$$extractPolymorphicRelationships(key, relationshipMeta, resourceHash, relationshipKey) { var polymorphicKey = activemodel$adapter$lib$system$active$model$serializer$$decamelize(key); if (polymorphicKey in resourceHash && typeof resourceHash[polymorphicKey] === 'object') { if (relationshipMeta.kind === 'belongsTo') { var hash = resourceHash[polymorphicKey]; var id = hash.id; var type = hash.type; resourceHash[relationshipKey] = { id: id, type: type }; // otherwise hasMany } else { var hashes = resourceHash[polymorphicKey]; if (!hashes) { return; } // TODO: replace this with map when ActiveModelAdapter branches for Ember Data 2.0 var array = []; for (var i = 0, _length = hashes.length; i < _length; i++) { var hash = hashes[i]; var id = hash.id; var type = hash.type; array.push({ id: id, type: type }); } resourceHash[relationshipKey] = array; } } } var activemodel$adapter$lib$system$active$model$serializer$$default = activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer; function ember$data$lib$system$container$proxy$$ContainerProxy(container) { this.container = container; } ember$data$lib$system$container$proxy$$ContainerProxy.prototype.aliasedFactory = function (path, preLookup) { var _this = this; return { create: function () { if (preLookup) { preLookup(); } return _this.container.lookup(path); } }; }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerAlias = function (source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecation = function (deprecated, valid) { var preLookupCallback = function () { Ember.deprecate('You tried to look up \'' + deprecated + '\', but this has been deprecated in favor of \'' + valid + '\'.', false, { id: 'ds.store.deprecated-lookup', until: '2.0.0' }); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecations = function (proxyPairs) { var i, proxyPair, deprecated, valid; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; var ember$data$lib$system$container$proxy$$default = ember$data$lib$system$container$proxy$$ContainerProxy; var activemodel$adapter$lib$setup$container$$default = activemodel$adapter$lib$setup$container$$setupActiveModelAdapter; function activemodel$adapter$lib$setup$container$$setupActiveModelAdapter(registry, application) { var proxy = new ember$data$lib$system$container$proxy$$default(registry); proxy.registerDeprecations([{ deprecated: "serializer:_ams", valid: "serializer:-active-model" }, { deprecated: "adapter:_ams", valid: "adapter:-active-model" }]); registry.register("serializer:-active-model", activemodel$adapter$lib$system$active$model$serializer$$default.extend({ isNewSerializerAPI: true })); registry.register("adapter:-active-model", activemodel$adapter$lib$system$active$model$adapter$$default); } /** @module ember-data */ var ember$data$lib$adapters$fixture$adapter$$get = Ember.get; var ember$data$lib$adapters$fixture$adapter$$fmt = Ember.String.fmt; var ember$data$lib$adapters$fixture$adapter$$indexOf = Ember.ArrayPolyfills.indexOf; var ember$data$lib$adapters$fixture$adapter$$counter = 0; var ember$data$lib$adapters$fixture$adapter$$default = ember$data$lib$system$adapter$$default.extend({ // by default, fixtures are already in normalized form serializer: null, // The fixture adapter does not support coalesceFindRequests coalesceFindRequests: false, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {DS.Model} typeClass @return {Array} */ fixturesForType: function (typeClass) { if (typeClass.FIXTURES) { var fixtures = Ember.A(typeClass.FIXTURES); return fixtures.map(function (fixture) { var fixtureIdType = typeof fixture.id; if (fixtureIdType !== "number" && fixtureIdType !== "string") { throw new Error(ember$data$lib$adapters$fixture$adapter$$fmt("the id property must be defined as a number or string for fixture %@", [fixture])); } fixture.id = fixture.id + ""; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixtures @param {Object} query @param {DS.Model} typeClass @return {(Promise|Array)} */ queryFixtures: function (fixtures, query, typeClass) { Ember.assert("Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store."); }, /** @method updateFixtures @param {DS.Model} typeClass @param {Array} fixture */ updateFixtures: function (typeClass, fixture) { if (!typeClass.FIXTURES) { typeClass.FIXTURES = []; } var fixtures = typeClass.FIXTURES; this.deleteLoadedFixture(typeClass, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {DS.Store} store @param {DS.Model} typeClass @param {DS.Snapshot} snapshot */ mockJSON: function (store, typeClass, snapshot) { return store.serializerFor(snapshot.modelName).serialize(snapshot, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @return {String} id */ generateIdForRecord: function (store) { return "fixture-" + ember$data$lib$adapters$fixture$adapter$$counter++; }, /** @method find @param {DS.Store} store @param {DS.Model} typeClass @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ find: function (store, typeClass, id, snapshot) { var fixtures = this.fixturesForType(typeClass); var fixture; Ember.assert("Unable to find fixtures for model type " + typeClass.toString() + ". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures); if (fixtures) { fixture = Ember.A(fixtures).findBy("id", id); } if (fixture) { return this.simulateRemoteCall(function () { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {DS.Model} typeClass @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, typeClass, ids, snapshots) { var fixtures = this.fixturesForType(typeClass); Ember.assert("Unable to find fixtures for model type " + typeClass.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function (item) { return ember$data$lib$adapters$fixture$adapter$$indexOf.call(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function () { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {DS.Model} typeClass @return {Promise} promise */ findAll: function (store, typeClass) { var fixtures = this.fixturesForType(typeClass); Ember.assert("Unable to find fixtures for model type " + typeClass.toString(), fixtures); return this.simulateRemoteCall(function () { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {DS.Model} typeClass @param {Object} query @param {DS.AdapterPopulatedRecordArray} array @return {Promise} promise */ findQuery: function (store, typeClass, query, array) { var fixtures = this.fixturesForType(typeClass); Ember.assert("Unable to find fixtures for model type " + typeClass.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, typeClass); if (fixtures) { return this.simulateRemoteCall(function () { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function (store, typeClass, snapshot) { var fixture = this.mockJSON(store, typeClass, snapshot); this.updateFixtures(typeClass, fixture); return this.simulateRemoteCall(function () { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, typeClass, snapshot) { var fixture = this.mockJSON(store, typeClass, snapshot); this.updateFixtures(typeClass, fixture); return this.simulateRemoteCall(function () { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function (store, typeClass, snapshot) { this.deleteLoadedFixture(typeClass, snapshot); return this.simulateRemoteCall(function () { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param typeClass @param snapshot */ deleteLoadedFixture: function (typeClass, snapshot) { var existingFixture = this.findExistingFixture(typeClass, snapshot); if (existingFixture) { var index = ember$data$lib$adapters$fixture$adapter$$indexOf.call(typeClass.FIXTURES, existingFixture); typeClass.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param typeClass @param snapshot */ findExistingFixture: function (typeClass, snapshot) { var fixtures = this.fixturesForType(typeClass); var id = snapshot.id; return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function (fixtures, id) { return Ember.A(fixtures).find(function (r) { if ("" + ember$data$lib$adapters$fixture$adapter$$get(r, "id") === "" + id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function (callback, context) { var adapter = this; return new Ember.RSVP.Promise(function (resolve) { var value = Ember.copy(callback.call(context), true); if (ember$data$lib$adapters$fixture$adapter$$get(adapter, "simulateRemoteResponse")) { // Schedule with setTimeout Ember.run.later(function () { resolve(value); }, ember$data$lib$adapters$fixture$adapter$$get(adapter, "latency")); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule("actions", null, function () { resolve(value); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); var ember$data$lib$adapters$json$api$adapter$$default = ember$data$lib$adapters$rest$adapter$$default.extend({ defaultSerializer: '-json-api', /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ 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; }, /** @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, type, ids, snapshots) { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); }, /** @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var dasherized = Ember.String.dasherize(modelName); return Ember.String.pluralize(dasherized); }, // TODO: Remove this once we have a better way to override HTTP verbs. /** @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, type, snapshot) { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data: data }); } }); var ember$data$lib$core$$DS = Ember.Namespace.create({ VERSION: '1.13.7' }); if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', ember$data$lib$core$$DS.VERSION); } //jshint ignore: line var ember$data$lib$core$$EMBER_DATA_FEATURES = {}; Ember.merge(Ember.FEATURES, ember$data$lib$core$$EMBER_DATA_FEATURES); var ember$data$lib$core$$default = ember$data$lib$core$$DS; var ember$data$lib$system$store$common$$get = Ember.get; function ember$data$lib$system$store$common$$_bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply(undefined, args); }; } function ember$data$lib$system$store$common$$_guard(promise, test) { var guarded = promise["finally"](function () { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function ember$data$lib$system$store$common$$_objectIsAlive(object) { return !(ember$data$lib$system$store$common$$get(object, "isDestroyed") || ember$data$lib$system$store$common$$get(object, "isDestroying")); } function ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(type); } if (serializer === null || serializer === undefined) { Ember.deprecate('Ember Data 2.0 will no longer support adapters with a null serializer property. Please define `defaultSerializer: "-default"` your adapter and make sure the `serializer` property is not null.', false, { id: 'ds.adapter.null-serializer-property', until: '2.0.0' }); serializer = { extract: function (store, type, payload) { return payload; } }; } return serializer; } var ember$data$lib$system$store$finders$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$store$finders$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$store$finders$$get = Ember.get; function ember$data$lib$system$store$finders$$_find(adapter, store, typeClass, id, internalModel, options) { var snapshot = internalModel.createSnapshot(options); var promise; if (!adapter.findRecord) { Ember.deprecate("Adapter#find has been deprecated and renamed to `findRecord`.", false, { id: "ds.adapter.find-renamed-to-find-record", until: "2.0.0" }); promise = adapter.find(store, typeClass, id, snapshot); } else { promise = adapter.findRecord(store, typeClass, id, snapshot); } var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, internalModel.type.modelName); var label = "DS: Handle Adapter#find of " + typeClass + " with id: " + id; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function (adapterPayload) { Ember.assert("You made a request for a " + typeClass.typeClassKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload); return store._adapterRun(function () { var requestType = ember$data$lib$system$store$finders$$get(serializer, "isNewSerializerAPI") ? "findRecord" : "find"; var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, id, requestType); //TODO Optimize var record = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); return record._internalModel; }); }, function (error) { internalModel.notFound(); if (internalModel.isEmpty()) { internalModel.unloadRecord(); } throw error; }, "DS: Extract payload of '" + typeClass + "'"); } function ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, internalModels) { var snapshots = Ember.A(internalModels).invoke("createSnapshot"); var promise = adapter.findMany(store, typeClass, ids, snapshots); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass.modelName); var label = "DS: Handle Adapter#findMany of " + typeClass; if (promise === undefined) { throw new Error("adapter.findMany returned undefined, this was very likely a mistake"); } promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, "findMany"); //TODO Optimize, no need to materialize here var records = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); return ember$data$lib$system$store$finders$$map.call(records, function (record) { return record._internalModel; }); }); }, null, "DS: Extract payload of " + typeClass); } function ember$data$lib$system$store$finders$$_findHasMany(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findHasMany(store, snapshot, link, relationship); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, "findHasMany"); //TODO Use a non record creating push var records = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); var recordArray = ember$data$lib$system$store$finders$$map.call(records, function (record) { return record._internalModel; }); if (ember$data$lib$system$store$finders$$get(serializer, "isNewSerializerAPI")) { recordArray.meta = payload.meta; } return recordArray; }); }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type); } function ember$data$lib$system$store$finders$$_findBelongsTo(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, "findBelongsTo"); if (!payload.data) { return null; } //TODO Optimize var record = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); return record._internalModel; }); }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type); } function ember$data$lib$system$store$finders$$_findAll(adapter, store, typeClass, sinceToken, options) { var modelName = typeClass.modelName; var recordArray = store.peekAll(modelName); var snapshotArray = recordArray.createSnapshot(options); var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName); var label = "DS: Handle Adapter#findAll of " + typeClass; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, "findAll"); //TODO Optimize ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); }); store.didUpdateAll(typeClass); return store.peekAll(modelName); }, null, "DS: Extract payload of findAll " + typeClass); } function ember$data$lib$system$store$finders$$_query(adapter, store, typeClass, query, recordArray) { var modelName = typeClass.modelName; var promise; if (!adapter.query) { Ember.deprecate("Adapter#findQuery has been deprecated and renamed to `query`.", false, { id: "ds.adapter.find-query-renamed-to-query", until: "2.0.0" }); promise = adapter.findQuery(store, typeClass, query, recordArray); } else { promise = adapter.query(store, typeClass, query, recordArray); } var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName); var label = "DS: Handle Adapter#findQuery of " + typeClass; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function (adapterPayload) { var records; store._adapterRun(function () { var requestType = ember$data$lib$system$store$finders$$get(serializer, "isNewSerializerAPI") ? "query" : "findQuery"; var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, requestType); //TODO Optimize records = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); }); recordArray.loadRecords(records); return recordArray; }, null, "DS: Extract payload of findQuery " + typeClass); } function ember$data$lib$system$store$finders$$_queryRecord(adapter, store, typeClass, query) { var modelName = typeClass.modelName; var promise = adapter.queryRecord(store, typeClass, query); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName); var label = "DS: Handle Adapter#queryRecord of " + typeClass; promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); return promise.then(function (adapterPayload) { var record; store._adapterRun(function () { var payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, "queryRecord"); //TODO Optimize record = ember$data$lib$system$store$serializer$response$$pushPayload(store, payload); }); return record; }, null, "DS: Extract payload of queryRecord " + typeClass); } function ember$data$lib$system$snapshot$record$array$$SnapshotRecordArray(recordArray, meta, adapterOptions) { /** 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 @property length @type {Number} */ this.length = recordArray.get('length'); /** The type of the underlying records for the snapshots in the array, as a DS.Model @property type @type {DS.Model} */ this.type = recordArray.get('type'); /** Meta object @property meta @type {Object} */ this.meta = meta; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = adapterOptions; } /** Get snapshots of the underlying record array @method snapshots @return {Array} Array of snapshots */ ember$data$lib$system$snapshot$record$array$$SnapshotRecordArray.prototype.snapshots = function () { if (this._snapshots) { return this._snapshots; } var recordArray = this._recordArray; this._snapshots = recordArray.invoke('createSnapshot'); return this._snapshots; }; var ember$data$lib$system$snapshot$record$array$$default = ember$data$lib$system$snapshot$record$array$$SnapshotRecordArray; var ember$data$lib$system$record$arrays$record$array$$get = Ember.get; var ember$data$lib$system$record$arrays$record$array$$set = Ember.set; var ember$data$lib$system$record$arrays$record$array$$default = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** 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 */ 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 */ 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 */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function (index) { var content = ember$data$lib$system$record$arrays$record$array$$get(this, "content"); var internalModel = 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(); people.get('isUpdating'); // true ``` @method update */ update: function () { if (ember$data$lib$system$record$arrays$record$array$$get(this, "isUpdating")) { return; } var store = ember$data$lib$system$record$arrays$record$array$$get(this, "store"); var modelName = ember$data$lib$system$record$arrays$record$array$$get(this, "type.modelName"); return store.findAll(modelName, { reload: true }); }, /** Adds an internal model to the `RecordArray` without duplicates @method addInternalModel @private @param {InternalModel} internalModel @param {number} an optional index to insert at */ addInternalModel: function (internalModel, idx) { var content = ember$data$lib$system$record$arrays$record$array$$get(this, "content"); if (idx === undefined) { content.addObject(internalModel); } else if (!content.contains(internalModel)) { content.insertAt(idx, internalModel); } }, /** Removes an internalModel to the `RecordArray`. @method removeInternalModel @private @param {InternalModel} internalModel */ removeInternalModel: function (internalModel) { ember$data$lib$system$record$arrays$record$array$$get(this, "content").removeObject(internalModel); }, /** 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 recordArray = this; var promiseLabel = "DS: RecordArray#save " + ember$data$lib$system$record$arrays$record$array$$get(this, "type"); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { return recordArray; }, null, "DS: RecordArray#save return RecordArray"); return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function () { var array = this; this.get("content").forEach(function (record) { var recordArrays = record._recordArrays; if (recordArrays) { recordArrays["delete"](array); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function () { var manager = ember$data$lib$system$record$arrays$record$array$$get(this, "manager"); manager.unregisterRecordArray(this); }, willDestroy: function () { this._unregisterFromManager(); this._dissociateFromOwnRecords(); ember$data$lib$system$record$arrays$record$array$$set(this, "content", undefined); this._super.apply(this, arguments); }, createSnapshot: function (options) { var adapterOptions = options && options.adapterOptions; var meta = this.get("meta"); return new ember$data$lib$system$snapshot$record$array$$default(this, meta, adapterOptions); } }); /** @module ember-data */ var ember$data$lib$system$record$arrays$filtered$record$array$$get = Ember.get; var ember$data$lib$system$record$arrays$filtered$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({ /** 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 */ filterFunction: null, isLoaded: true, replace: function () { var type = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type").toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function () { var manager = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "manager"); manager.updateFilter(this, ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type"), ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "filterFunction")); }, updateFilter: Ember.observer("filterFunction", function () { Ember.run.once(this, this._updateFilter); }) }); var ember$data$lib$system$clone$null$$default = ember$data$lib$system$clone$null$$cloneNull; function ember$data$lib$system$clone$null$$cloneNull(source) { var clone = ember$data$lib$system$object$polyfills$$create(null); for (var key in source) { clone[key] = source[key]; } return clone; } /** @module ember-data */ var ember$data$lib$system$record$arrays$adapter$populated$record$array$$get = Ember.get; var ember$data$lib$system$record$arrays$adapter$populated$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({ query: null, replace: function () { var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type").toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function (data) { var store = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "store"); var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type"); var modelName = type.modelName; var records = store.pushMany(modelName, data); this.loadRecords(records); }, /** @method loadRecords @param {Array} records @private */ loadRecords: function (records) { var store = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "store"); var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type"); var modelName = type.modelName; var meta = store._metadataFor(modelName); //TODO Optimize var internalModels = Ember.A(records).mapBy("_internalModel"); this.setProperties({ content: Ember.A(internalModels), isLoaded: true, meta: ember$data$lib$system$clone$null$$default(meta) }); internalModels.forEach(function (record) { this.manager.recordArraysForRecord(record).add(this); }, this); // TODO: should triggering didLoad event be the last action of the runLoop? Ember.run.once(this, "trigger", "didLoad"); } }); var ember$data$lib$system$ordered$set$$EmberOrderedSet = Ember.OrderedSet; var ember$data$lib$system$ordered$set$$guidFor = Ember.guidFor; var ember$data$lib$system$ordered$set$$OrderedSet = function () { this._super$constructor(); }; ember$data$lib$system$ordered$set$$OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; ember$data$lib$system$ordered$set$$OrderedSet.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$system$ordered$set$$EmberOrderedSet.prototype); ember$data$lib$system$ordered$set$$OrderedSet.prototype.constructor = ember$data$lib$system$ordered$set$$OrderedSet; ember$data$lib$system$ordered$set$$OrderedSet.prototype._super$constructor = ember$data$lib$system$ordered$set$$EmberOrderedSet; ember$data$lib$system$ordered$set$$OrderedSet.prototype.addWithIndex = function (obj, idx) { var guid = ember$data$lib$system$ordered$set$$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; }; var ember$data$lib$system$ordered$set$$default = ember$data$lib$system$ordered$set$$OrderedSet; var ember$data$lib$system$record$array$manager$$get = Ember.get; var ember$data$lib$system$record$array$manager$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$record$array$manager$$indexOf = Ember.ArrayPolyfills.indexOf; var ember$data$lib$system$record$array$manager$$default = Ember.Object.extend({ init: function () { var _this = this; this.filteredRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function () { return []; } }); this.liveRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function (typeClass) { return _this.createRecordArray(typeClass); } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function (record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule("actions", this, this.updateRecordArrays); }, recordArraysForRecord: function (record) { record._recordArrays = record._recordArrays || ember$data$lib$system$ordered$set$$default.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays */ updateRecordArrays: function () { ember$data$lib$system$record$array$manager$$forEach.call(this.changedRecords, function (record) { if (record.isDeleted()) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function (array) { array.removeInternalModel(record); }); record._recordArrays = null; }, _recordWasChanged: function (record) { var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; ember$data$lib$system$record$array$manager$$forEach.call(recordArrays, function (array) { filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction"); this.updateFilterRecordArray(array, filter, typeClass, record); }, this); }, //Need to update live arrays on loading recordWasLoaded: function (record) { var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; ember$data$lib$system$record$array$manager$$forEach.call(recordArrays, function (array) { filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction"); this.updateFilterRecordArray(array, filter, typeClass, record); }, this); if (this.liveRecordArrays.has(typeClass)) { var liveRecordArray = this.liveRecordArrays.get(typeClass); this._addRecordToRecordArray(liveRecordArray, record); } }, /** Update an individual filter. @method updateFilterRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {DS.Model} typeClass @param {InternalModel} record */ updateFilterRecordArray: function (array, filter, typeClass, record) { var shouldBeInArray = filter(record.getRecord()); var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { this._addRecordToRecordArray(array, record); } else { recordArrays["delete"](array); array.removeInternalModel(record); } }, _addRecordToRecordArray: function (array, record) { var recordArrays = this.recordArraysForRecord(record); if (!recordArrays.has(array)) { array.addInternalModel(record); recordArrays.add(array); } }, populateLiveRecordArray: function (array, modelName) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0, l = records.length; i < l; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this._addRecordToRecordArray(array, record); } } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param {Array} array @param {String} modelName @param {Function} filter */ updateFilter: function (array, modelName, filter) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0, l = records.length; i < l; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this.updateFilterRecordArray(array, filter, modelName, record); } } }, /** Get the `DS.RecordArray` for a type, which contains all loaded records of given type. @method liveRecordArrayFor @param {Class} typeClass @return {DS.RecordArray} */ liveRecordArrayFor: function (typeClass) { return this.liveRecordArrays.get(typeClass); }, /** Create a `DS.RecordArray` for a type. @method createRecordArray @param {Class} typeClass @return {DS.RecordArray} */ createRecordArray: function (typeClass) { var array = ember$data$lib$system$record$arrays$record$array$$default.create({ type: typeClass, content: Ember.A(), store: this.store, isLoaded: true, manager: this }); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {DS.Model} typeClass @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function (typeClass, filter, query) { var array = ember$data$lib$system$record$arrays$filtered$record$array$$default.create({ query: query, type: typeClass, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, typeClass, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {DS.Model} typeClass @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function (typeClass, query) { var array = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default.create({ type: typeClass, query: query, content: Ember.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {DS.Model} typeClass @param {Function} filter */ registerFilteredRecordArray: function (array, typeClass, filter) { var recordArrays = this.filteredRecordArrays.get(typeClass); recordArrays.push(array); this.updateFilter(array, typeClass, filter); }, /** Unregister a RecordArray. So manager will not update this array. @method unregisterRecordArray @param {DS.RecordArray} array */ unregisterRecordArray: function (array) { var typeClass = array.type; // unregister filtered record array var recordArrays = this.filteredRecordArrays.get(typeClass); var index = ember$data$lib$system$record$array$manager$$indexOf.call(recordArrays, array); if (index !== -1) { recordArrays.splice(index, 1); // unregister live record array } else if (this.liveRecordArrays.has(typeClass)) { var liveRecordArrayForType = this.liveRecordArrayFor(typeClass); if (array === liveRecordArrayForType) { this.liveRecordArrays["delete"](typeClass); } } }, willDestroy: function () { this._super.apply(this, arguments); this.filteredRecordArrays.forEach(function (value) { ember$data$lib$system$record$array$manager$$forEach.call(ember$data$lib$system$record$array$manager$$flatten(value), ember$data$lib$system$record$array$manager$$destroy); }); this.liveRecordArrays.forEach(ember$data$lib$system$record$array$manager$$destroy); ember$data$lib$system$record$array$manager$$forEach.call(this._adapterPopulatedRecordArrays, ember$data$lib$system$record$array$manager$$destroy); } }); function ember$data$lib$system$record$array$manager$$destroy(entry) { entry.destroy(); } function ember$data$lib$system$record$array$manager$$flatten(list) { var length = list.length; var result = Ember.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } /** * The `ContainerInstanceCache` serves as a lazy cache for looking up * instances of serializers and adapters. It has some additional logic for * finding the 'fallback' adapter or serializer. * * The 'fallback' adapter or serializer is an adapter or serializer that is looked up * when the preferred lookup fails. For example, say you try to look up `adapter:post`, * but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry. * * The `fallbacks` array passed will then be used; the first entry in the fallbacks array * that exists in the container will then be cached for `adapter:post`. So, the next time you * look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback * was if `adapter:application` doesn't exist). * * @private * @class ContainerInstanceCache * */ function ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache(container) { this._container = container; this._cache = ember$data$lib$system$object$polyfills$$create(null); } ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype = ember$data$lib$system$object$polyfills$$create(null); ember$lib$main$$default.merge(ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype, { get: function (type, preferredKey, fallbacks) { var cache = this._cache; var preferredLookupKey = type + ':' + preferredKey; if (!(preferredLookupKey in cache)) { var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks); if (instance) { cache[preferredLookupKey] = instance; } } return cache[preferredLookupKey]; }, _findInstance: function (type, fallbacks) { for (var i = 0, _length = fallbacks.length; i < _length; i++) { var fallback = fallbacks[i]; var lookupKey = type + ':' + fallback; var instance = this.instanceFor(lookupKey); if (instance) { return instance; } } }, instanceFor: function (key) { if (key === 'adapter:-rest') { ember$lib$main$$default.deprecate('You are currently using the default DS.RESTAdapter adapter. For Ember 2.0 the default adapter will be DS.JSONAPIAdapter. If you would like to continue using DS.RESTAdapter please create an application adapter that extends DS.RESTAdapter.', false, { id: 'ds.adapter.default-adapter-changing-to-json-api', until: '2.0.0' }); } var cache = this._cache; if (!cache[key]) { var instance = this._container.lookup(key); if (instance) { cache[key] = instance; } } return cache[key]; }, destroy: function () { var cache = this._cache; var cacheEntries = ember$data$lib$system$object$polyfills$$keysFunc(cache); for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) { var cacheKey = cacheEntries[i]; var cacheEntry = cache[cacheKey]; if (cacheEntry) { cacheEntry.destroy(); } } this._container = null; }, constructor: ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache, toString: function () { return 'ContainerInstanceCache'; } }); var ember$data$lib$system$store$container$instance$cache$$default = ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache; function ember$data$lib$system$merge$$merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = ember$data$lib$system$object$polyfills$$keysFunc(updates); var prop; var length = props.length; for (var i = 0; i < length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } var ember$data$lib$system$merge$$default = ember$data$lib$system$merge$$merge; /** @module ember-data */ var ember$data$lib$system$model$states$$get = Ember.get; /* 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) * [isDirty](DS.Model.html#property_isDirty) * [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 ember$data$lib$system$model$states$$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.updateRecordArraysLater(); } // 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. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * 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 // send to the adapter yet. var ember$data$lib$system$model$states$$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: ember$data$lib$system$model$states$$didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: Ember.K, propertyWasReset: function (internalModel, name) { var length = ember$data$lib$system$object$polyfills$$keysFunc(internalModel._attributes).length; var stillDirty = length > 0; if (!stillDirty) { internalModel.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, 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: ember$data$lib$system$model$states$$didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function (internalModel) { var dirtyType = ember$data$lib$system$model$states$$get(this, 'dirtyType'); internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks', 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, // EVENTS deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); internalModel.disconnectRelationships(); }, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); ember$data$lib$system$model$states$$didSetProperty(internalModel, context); }, becomeDirty: Ember.K, pushedData: Ember.K, 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); }, exit: function (internalModel) { internalModel._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function ember$data$lib$system$model$states$$deepClone(object) { var clone = {}; var value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = ember$data$lib$system$model$states$$deepClone(value); } else { clone[prop] = value; } } return clone; } function ember$data$lib$system$model$states$$mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function ember$data$lib$system$model$states$$dirtyState(options) { var newState = ember$data$lib$system$model$states$$deepClone(ember$data$lib$system$model$states$$DirtyState); return ember$data$lib$system$model$states$$mixin(newState, options); } var ember$data$lib$system$model$states$$createdState = ember$data$lib$system$model$states$$dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); ember$data$lib$system$model$states$$createdState.invalid.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; ember$data$lib$system$model$states$$createdState.uncommitted.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; var ember$data$lib$system$model$states$$updatedState = ember$data$lib$system$model$states$$dirtyState({ dirtyType: 'updated' }); ember$data$lib$system$model$states$$createdState.uncommitted.deleteRecord = function (internalModel) { internalModel.disconnectRelationships(); internalModel.transitionTo('deleted.saved'); internalModel.send('invokeLifecycleCallbacks'); }; ember$data$lib$system$model$states$$createdState.uncommitted.rollback = function (internalModel) { ember$data$lib$system$model$states$$DirtyState.uncommitted.rollback.apply(this, arguments); internalModel.transitionTo('deleted.saved'); }; ember$data$lib$system$model$states$$createdState.uncommitted.pushedData = function (internalModel) { internalModel.transitionTo('loaded.updated.uncommitted'); internalModel.triggerLater('didLoad'); }; ember$data$lib$system$model$states$$createdState.uncommitted.propertyWasReset = Ember.K; function ember$data$lib$system$model$states$$assertAgainstUnloadRecord(internalModel) { Ember.assert('You can only unload a record which is not inFlight. `' + internalModel + '`', false); } ember$data$lib$system$model$states$$updatedState.inFlight.unloadRecord = ember$data$lib$system$model$states$$assertAgainstUnloadRecord; ember$data$lib$system$model$states$$updatedState.uncommitted.deleteRecord = function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); internalModel.disconnectRelationships(); }; var ember$data$lib$system$model$states$$RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, propertyWasReset: Ember.K, // 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, // EVENTS 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; }, // EVENTS 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, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: Ember.K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function (internalModel) { var attrs = internalModel._attributes; var isDirty = ember$data$lib$system$object$polyfills$$keysFunc(attrs).length > 0; if (isDirty) { internalModel.adapterDidDirty(); } }, // EVENTS didSetProperty: ember$data$lib$system$model$states$$didSetProperty, pushedData: Ember.K, 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'); internalModel.disconnectRelationships(); }, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, didCommit: function (internalModel) { internalModel.send('invokeLifecycleCallbacks', ember$data$lib$system$model$states$$get(internalModel, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: ember$data$lib$system$model$states$$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: ember$data$lib$system$model$states$$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, // TRANSITIONS 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: { // EVENTS willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); }, pushedData: Ember.K, becomeDirty: Ember.K, deleteRecord: Ember.K, 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: ember$data$lib$system$model$states$$assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, 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) { var store = internalModel.store; store._dematerializeRecord(internalModel); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('didDelete', internalModel); internalModel.triggerLater('didCommit', internalModel); }, willCommit: Ember.K, didCommit: Ember.K }, invalid: { isValid: false, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); ember$data$lib$system$model$states$$didSetProperty(internalModel, context); }, deleteRecord: Ember.K, becomeDirty: Ember.K, willCommit: Ember.K, 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 ember$data$lib$system$model$states$$wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = ember$data$lib$system$model$states$$mixin(parent ? ember$data$lib$system$object$polyfills$$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] = ember$data$lib$system$model$states$$wireState(object[prop], object, name + '.' + prop); } } return object; } ember$data$lib$system$model$states$$RootState = ember$data$lib$system$model$states$$wireState(ember$data$lib$system$model$states$$RootState, null, 'root'); var ember$data$lib$system$model$states$$default = ember$data$lib$system$model$states$$RootState; var ember$data$lib$system$relationships$state$relationship$$forEach = Ember.ArrayPolyfills.forEach; function ember$data$lib$system$relationships$state$relationship$$Relationship(store, record, inverseKey, relationshipMeta) { this.members = new ember$data$lib$system$ordered$set$$default(); this.canonicalMembers = new ember$data$lib$system$ordered$set$$default(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.isAsync = relationshipMeta.options.async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible modelNames this.inverseKeyForImplicit = this.record.constructor.modelName + this.key; this.linkPromise = null; this.meta = null; this.hasData = false; } ember$data$lib$system$relationships$state$relationship$$Relationship.prototype = { constructor: ember$data$lib$system$relationships$state$relationship$$Relationship, destroy: Ember.K, updateMeta: function (meta) { this.meta = meta; }, clear: function () { var members = this.members.list; var member; while (members.length > 0) { member = members[0]; this.removeRecord(member); } }, disconnect: function () { this.members.forEach(function (member) { this.removeRecordFromInverse(member); }, this); }, reconnect: function () { this.members.forEach(function (member) { this.addRecordToInverse(member); }, this); }, removeRecords: function (records) { var self = this; ember$data$lib$system$relationships$state$relationship$$forEach.call(records, function (record) { self.removeRecord(record); }); }, addRecords: function (records, idx) { var self = this; ember$data$lib$system$relationships$state$relationship$$forEach.call(records, function (record) { self.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.addCanonicalRecord(records[i], i + idx); } else { this.addCanonicalRecord(records[i]); } } }, addCanonicalRecord: function (record, idx) { if (!this.canonicalMembers.has(record)) { this.canonicalMembers.add(record); if (this.inverseKey) { record._relationships.get(this.inverseKey).addCanonicalRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); } } this.flushCanonicalLater(); this.setHasData(true); }, removeCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.removeCanonicalRecord(records[i], i + idx); } else { this.removeCanonicalRecord(records[i]); } } }, removeCanonicalRecord: function (record, idx) { if (this.canonicalMembers.has(record)) { this.removeCanonicalRecordFromOwn(record); if (this.inverseKey) { this.removeCanonicalRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); } } } this.flushCanonicalLater(); }, addRecord: function (record, idx) { if (!this.members.has(record)) { this.members.addWithIndex(record, idx); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships.get(this.inverseKey).addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArraysLater(); } this.setHasData(true); }, removeRecord: function (record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, addRecordToInverse: function (record) { if (this.inverseKey) { record._relationships.get(this.inverseKey).addRecord(this.record); } }, removeRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function (record) { this.members["delete"](record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, removeCanonicalRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalRecordFromOwn(this.record); } }, removeCanonicalRecordFromOwn: function (record) { this.canonicalMembers["delete"](record); this.flushCanonicalLater(); }, flushCanonical: function () { this.willSync = false; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = []; for (var i = 0; i < this.members.list.length; i++) { if (this.members.list[i].isNew()) { newRecords.push(this.members.list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (i = 0; i < newRecords.length; i++) { this.members.add(newRecords[i]); } }, flushCanonicalLater: function () { if (this.willSync) { return; } this.willSync = true; var self = this; this.store._backburner.join(function () { self.store._backburner.schedule('syncRelationships', self, self.flushCanonical); }); }, updateLink: function (link) { Ember.warn('You have pushed a record of type \'' + this.record.type.modelName + '\' with \'' + this.key + '\' as a link, but the association is not an async relationship.', this.isAsync, { id: 'ds.store.push-link-for-sync-relationship' }); Ember.assert('You have pushed a record of type \'' + this.record.type.modelName + '\' with \'' + this.key + '\' as a link, but the value of that link is not a string.', typeof link === 'string' || link === null); if (link !== this.link) { this.link = link; this.linkPromise = null; this.record.notifyPropertyChange(this.key); } }, findLink: function () { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function (result) { return result; }); } }, updateRecordsFromAdapter: function (records) { //TODO(Igor) move this to a proper place var self = this; //TODO Once we have adapter support, we need to handle updated and canonical changes self.computeChanges(records); self.setHasData(true); }, notifyRecordRelationshipAdded: Ember.K, notifyRecordRelationshipRemoved: Ember.K, setHasData: function (value) { this.hasData = value; } }; var ember$data$lib$system$relationships$state$relationship$$default = ember$data$lib$system$relationships$state$relationship$$Relationship; var ember$data$lib$system$many$array$$get = Ember.get; var ember$data$lib$system$many$array$$set = Ember.set; var ember$data$lib$system$many$array$$filter = Ember.ArrayPolyfills.filter; var ember$data$lib$system$many$array$$default = Ember.Object.extend(Ember.MutableArray, Ember.Evented, { init: function () { this.currentState = Ember.A([]); }, record: null, canonicalState: null, currentState: null, length: 0, objectAt: function (index) { //Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses if (!this.currentState[index]) { return undefined; } return this.currentState[index].getRecord(); }, flushCanonical: function () { //TODO make this smarter, currently its plenty stupid var toSet = ember$data$lib$system$many$array$$filter.call(this.canonicalState, function (internalModel) { return !internalModel.isDeleted(); }); //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = this.currentState.filter(function (internalModel) { return internalModel.isNew(); }); toSet = toSet.concat(newRecords); var oldLength = this.length; this.arrayContentWillChange(0, this.length, toSet.length); this.set('length', toSet.length); this.currentState = toSet; this.arrayContentDidChange(0, oldLength, this.length); //TODO Figure out to notify only on additions and maybe only if unloaded this.relationship.notifyHasManyChanged(); this.record.updateRecordArrays(); }, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, /** The loading state of this array @property {Boolean} isLoaded */ isLoaded: false, /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ relationship: 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 */ meta: null, 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); if (objects) { //TODO(Igor) probably needed only for unloaded records this.relationship.notifyHasManyChanged(); } this.record.updateRecordArrays(); }, //TODO(Igor) optimize internalRemoveRecords: function (records) { var index; for (var i = 0; i < records.length; i++) { index = this.currentState.indexOf(records[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize internalAddRecords: function (records, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, records); }, replace: function (idx, amt, objects) { var records; if (amt > 0) { records = this.currentState.slice(idx, idx + amt); this.get('relationship').removeRecords(records); } var map = objects.map || Ember.ArrayPolyfills.map; if (objects) { this.get('relationship').addRecords(map.call(objects, function (obj) { return obj._internalModel; }), idx); } }, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function (count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function () { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { ember$data$lib$system$many$array$$set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method reload @public */ reload: function () { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.find('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 ' + ember$data$lib$system$many$array$$get(this, 'type'); var promise = Ember.RSVP.all(this.invoke('save'), promiseLabel).then(function (array) { return manyArray; }, null, 'DS: ManyArray#save return ManyArray'); return ember$data$lib$system$promise$proxies$$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 = ember$data$lib$system$many$array$$get(this, 'store'); var type = ember$data$lib$system$many$array$$get(this, 'type'); var record; Ember.assert('You cannot add \'' + type.modelName + '\' records to this polymorphic relationship.', !ember$data$lib$system$many$array$$get(this, 'isPolymorphic')); record = store.createRecord(type.modelName, hash); this.pushObject(record); return record; }, /** @method addRecord @param {DS.Model} record @deprecated Use `addObject()` instead */ addRecord: function (record) { Ember.deprecate('Using manyArray.addRecord() has been deprecated. You should use manyArray.addObject() instead.', false, { id: 'ds.many-array.add-record-deprecated', until: '2.0.0' }); this.addObject(record); }, /** @method removeRecord @param {DS.Model} record @deprecated Use `removeObject()` instead */ removeRecord: function (record) { Ember.deprecate('Using manyArray.removeRecord() has been deprecated. You should use manyArray.removeObject() instead.', false, { id: 'ds.many-array.remove-record-deprecated', until: '2.0.0' }); this.removeObject(record); } }); /** 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} record @param {RelationshipMeta} relationshipMeta retrieved via `record.relationshipFor(key)` @param {InternalModel} addedRecord record which should be added/set for the relationship */ var ember$data$lib$utils$$assertPolymorphicType = function (record, relationshipMeta, addedRecord) { var addedType = addedRecord.type.modelName; var recordType = record.type.modelName; var key = relationshipMeta.key; var typeClass = record.store.modelFor(relationshipMeta.type); var assertionMessage = 'You cannot add a record of type \'' + addedType + '\' to the \'' + recordType + '.' + key + '\' relationship (only \'' + typeClass.modelName + '\' allowed)'; ember$lib$main$$default.assert(assertionMessage, ember$data$lib$utils$$checkPolymorphic(typeClass, addedRecord)); }; function ember$data$lib$utils$$checkPolymorphic(typeClass, addedRecord) { if (typeClass.__isMixin) { //TODO Need to do this in order to support mixins, should convert to public api //once it exists in Ember return typeClass.__mixin.detect(addedRecord.type.PrototypeMixin); } if (ember$lib$main$$default.MODEL_FACTORY_INJECTIONS) { typeClass = typeClass.superclass; } return typeClass.detect(addedRecord.type); } var ember$data$lib$system$relationships$state$has$many$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$relationships$state$has$many$$ManyRelationship = function (store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.canonicalState = []; this.manyArray = ember$data$lib$system$many$array$$default.create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.store.modelFor(this.belongsToType), record: record }); this.isPolymorphic = relationshipMeta.options.polymorphic; this.manyArray.isPolymorphic = this.isPolymorphic; }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$system$relationships$state$relationship$$default.prototype); ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.constructor = ember$data$lib$system$relationships$state$has$many$$ManyRelationship; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.destroy = function () { this.manyArray.destroy(); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$updateMeta = ember$data$lib$system$relationships$state$relationship$$default.prototype.updateMeta; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.updateMeta = function (meta) { this._super$updateMeta(meta); this.manyArray.set("meta", meta); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addCanonicalRecord = function (record, idx) { if (this.canonicalMembers.has(record)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, record); } else { this.canonicalState.push(record); } this._super$addCanonicalRecord(record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addRecord = function (record, idx) { if (this.members.has(record)) { return; } this._super$addRecord(record, idx); this.manyArray.internalAddRecords([record], idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) { var i = idx; if (!this.canonicalMembers.has(record)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(record); } if (i > -1) { this.canonicalState.splice(i, 1); } this._super$removeCanonicalRecordFromOwn(record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.flushCanonical = function () { this.manyArray.flushCanonical(); this._super$flushCanonical(); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) { if (!this.members.has(record)) { return; } this._super$removeRecordFromOwn(record, idx); if (idx !== undefined) { //TODO(Igor) not used currently, fix this.manyArray.currentState.removeAt(idx); } else { this.manyArray.internalRemoveRecords([record]); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) { ember$data$lib$utils$$assertPolymorphicType(this.record, this.relationshipMeta, record); this.record.notifyHasManyAdded(this.key, record, idx); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.reload = function () { var self = this; if (this.link) { return this.fetchLink(); } else { return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () { //Goes away after the manyArray refactor self.manyArray.set("isLoaded", true); return self.manyArray; }); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.computeChanges = function (records) { var members = this.canonicalMembers; var recordsToRemove = []; var length; var record; var i; records = ember$data$lib$system$relationships$state$has$many$$setForArray(records); members.forEach(function (member) { if (records.has(member)) { return; } recordsToRemove.push(member); }); this.removeCanonicalRecords(recordsToRemove); // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++) { record = records[i]; this.removeCanonicalRecord(record); this.addCanonicalRecord(record, i); } }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.fetchLink = function () { var _this = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) { if (records.hasOwnProperty("meta")) { _this.updateMeta(records.meta); } _this.store._backburner.join(function () { _this.updateRecordsFromAdapter(records); }); return _this.manyArray; }); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.findRecords = function () { var manyArray = this.manyArray; //TODO CLEANUP return this.store.findMany(ember$data$lib$system$relationships$state$has$many$$map.call(manyArray.toArray(), function (rec) { return rec._internalModel; })).then(function () { //Goes away after the manyArray refactor manyArray.set("isLoaded", true); return manyArray; }); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyHasManyChanged = function () { this.record.notifyHasManyAdded(this.key); }; ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.getRecords = function () { //TODO(Igor) sync server here, once our syncing is not stupid if (this.isAsync) { var self = this; var promise; if (this.link) { promise = this.findLink().then(function () { return self.findRecords(); }); } else { promise = this.findRecords(); } return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({ content: this.manyArray, promise: promise }); } else { Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.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 })`)", this.manyArray.isEvery("isEmpty", false)); //TODO(Igor) WTF DO I DO HERE? if (!this.manyArray.get("isDestroyed")) { this.manyArray.set("isLoaded", true); } return this.manyArray; } }; function ember$data$lib$system$relationships$state$has$many$$setForArray(array) { var set = new ember$data$lib$system$ordered$set$$default(); if (array) { for (var i = 0, l = array.length; i < l; i++) { set.add(array[i]); } } return set; } var ember$data$lib$system$relationships$state$has$many$$default = ember$data$lib$system$relationships$state$has$many$$ManyRelationship; var ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship = function (store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; this.canonicalState = null; }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype = ember$data$lib$system$object$polyfills$$create(ember$data$lib$system$relationships$state$relationship$$default.prototype); ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.constructor = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecord = function (newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.setHasData(true); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) { if (newRecord) { this.addCanonicalRecord(newRecord); } else if (this.inverseRecord) { this.removeCanonicalRecord(this.inverseRecord); } this.setHasData(true); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) { if (this.canonicalMembers.has(newRecord)) { return; } if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.canonicalState = newRecord; this._super$addCanonicalRecord(newRecord); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.flushCanonical = function () { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) { return; } this.inverseRecord = this.canonicalState; this.record.notifyBelongsToChanged(this.key); this._super$flushCanonical(); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addRecord = function (newRecord) { if (this.members.has(newRecord)) { return; } ember$data$lib$utils$$assertPolymorphicType(this.record, this.relationshipMeta, newRecord); if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); this.record.notifyBelongsToChanged(this.key); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecordPromise = function (newPromise) { var content = newPromise.get && newPromise.get("content"); Ember.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.setRecord(content ? content._internalModel : content); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeRecordFromOwn = function (record) { if (!this.members.has(record)) { return; } this.inverseRecord = null; this._super$removeRecordFromOwn(record); this.record.notifyBelongsToChanged(this.key); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) { if (!this.canonicalMembers.has(record)) { return; } this.canonicalState = null; this._super$removeCanonicalRecordFromOwn(record); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.findRecord = function () { if (this.inverseRecord) { return this.store._findByInternalModel(this.inverseRecord); } else { return Ember.RSVP.Promise.resolve(null); } }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.fetchLink = function () { var self = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) { if (record) { self.addRecord(record); } return record; }); }; ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.getRecord = function () { //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { var self = this; promise = this.findLink().then(function () { return self.findRecord(); }); } else { promise = this.findRecord(); } return ember$data$lib$system$promise$proxies$$PromiseObject.create({ promise: promise, content: this.inverseRecord ? this.inverseRecord.getRecord() : null }); } else { if (this.inverseRecord === null) { return null; } var toReturn = this.inverseRecord.getRecord(); Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.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; } }; var ember$data$lib$system$relationships$state$belongs$to$$default = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship; var ember$data$lib$system$relationships$state$create$$get = Ember.get; var ember$data$lib$system$relationships$state$create$$createRelationshipFor = function (record, relationshipMeta, store) { var inverseKey; var inverse = record.type.inverseFor(relationshipMeta.key, store); if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === "hasMany") { return new ember$data$lib$system$relationships$state$has$many$$default(store, record, inverseKey, relationshipMeta); } else { return new ember$data$lib$system$relationships$state$belongs$to$$default(store, record, inverseKey, relationshipMeta); } }; var ember$data$lib$system$relationships$state$create$$Relationships = function (record) { this.record = record; this.initializedRelationships = ember$data$lib$system$object$polyfills$$create(null); }; ember$data$lib$system$relationships$state$create$$Relationships.prototype.has = function (key) { return !!this.initializedRelationships[key]; }; ember$data$lib$system$relationships$state$create$$Relationships.prototype.get = function (key) { var relationships = this.initializedRelationships; var relationshipsByName = ember$data$lib$system$relationships$state$create$$get(this.record.type, "relationshipsByName"); if (!relationships[key] && relationshipsByName.get(key)) { relationships[key] = ember$data$lib$system$relationships$state$create$$createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store); } return relationships[key]; }; var ember$data$lib$system$relationships$state$create$$default = ember$data$lib$system$relationships$state$create$$Relationships; /** @module ember-data */ var ember$data$lib$system$snapshot$$get = Ember.get;/** @class Snapshot @namespace DS @private @constructor @param {DS.Model} internalModel The model to create a snapshot from */ function ember$data$lib$system$snapshot$$Snapshot(internalModel) { this._attributes = ember$data$lib$system$object$polyfills$$create(null); this._belongsToRelationships = ember$data$lib$system$object$polyfills$$create(null); this._belongsToIds = ember$data$lib$system$object$polyfills$$create(null); this._hasManyRelationships = ember$data$lib$system$object$polyfills$$create(null); this._hasManyIds = ember$data$lib$system$object$polyfills$$create(null); var record = internalModel.getRecord(); this.record = record; record.eachAttribute(function (keyName) { this._attributes[keyName] = ember$data$lib$system$snapshot$$get(record, keyName); }, this); this.id = internalModel.id; this._internalModel = internalModel; this.type = internalModel.type; this.modelName = internalModel.type.modelName; this._changedAttributes = record.changedAttributes(); // The following code is here to keep backwards compatibility when accessing // `constructor` directly. // // With snapshots you should use `type` instead of `constructor`. // // Remove for Ember Data 1.0. if (Ember.platform.hasPropertyAccessors) { var callDeprecate = true; Ember.defineProperty(this, 'constructor', { get: function () { // Ugly hack since accessing error.stack (done in `Ember.deprecate()`) // causes the internals of Chrome to access the constructor, which then // causes an infinite loop if accessed and calls `Ember.deprecate()` // again. if (callDeprecate) { callDeprecate = false; Ember.deprecate('Usage of `snapshot.constructor` is deprecated, use `snapshot.type` instead.', false, { id: 'ds.snapshot.constructor-deprecator', until: '2.0.0' }); callDeprecate = true; } return this.type; } }); } else { this.constructor = this.type; } } ember$data$lib$system$snapshot$$Snapshot.prototype = { constructor: ember$data$lib$system$snapshot$$Snapshot, /** 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} */ id: null, /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript var json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ record: null, /** The type of the underlying record for this snapshot, as a DS.Model. @property type @type {DS.Model} */ type: null, /** The name of the type of the underlying record for this snapshot, as a string. @property modelName @type {String} */ modelName: null, /** Returns the value of an attribute. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attr('author'); // => 'Tomster' postSnapshot.attr('title'); // => 'Ember.js rocks' ``` Note: Values are loaded eagerly and cached when the snapshot is created. @method attr @param {String} keyName @return {Object} The attribute value or undefined */ attr: function (keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no attribute named \'' + keyName + '\' defined.'); }, /** Returns all attributes and their corresponding values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } ``` @method attributes @return {Object} All attributes of the current snapshot */ attributes: function () { return Ember.copy(this._attributes); }, /** Returns all changed attributes and their old and new values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postModel.set('title', 'Ember.js rocks!'); postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } ``` @method changedAttributes @return {Object} All changed attributes of the current snapshot */ changedAttributes: function () { var changedAttributes = ember$data$lib$system$object$polyfills$$create(null); var changedAttributeKeys = ember$data$lib$system$object$polyfills$$keysFunc(this._changedAttributes); for (var i = 0, _length = changedAttributeKeys.length; i < _length; i++) { var key = changedAttributeKeys[i]; changedAttributes[key] = Ember.copy(this._changedAttributes[key]); } return changedAttributes; }, /** Returns the current value of a belongsTo relationship. `belongsTo` takes an optional hash of options as a second parameter, currently supported options are: - `id`: set to `true` if you only want the ID of the related record to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World' }); // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); commentSnapshot.belongsTo('post'); // => DS.Snapshot commentSnapshot.belongsTo('post', { id: true }); // => '1' // store.push('comment', { id: 1, body: 'Lorem ipsum' }); commentSnapshot.belongsTo('post'); // => undefined ``` Calling `belongsTo` will return a new Snapshot as long as there's any known data for the relationship available, such as an ID. If the relationship is known but unset, `belongsTo` will return `null`. If the contents of the relationship is unknown `belongsTo` will return `undefined`. Note: Relationships are loaded lazily and cached upon first access. @method belongsTo @param {String} keyName @param {Object} [options] @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known relationship or null if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ belongsTo: function (keyName, options) { var id = options && options.id; var relationship, inverseRecord, hasData; var result; 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.Error('Model \'' + Ember.inspect(this.record) + '\' has no belongsTo relationship named \'' + keyName + '\' defined.'); } hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData'); inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord'); if (hasData) { if (inverseRecord && !inverseRecord.isDeleted()) { if (id) { result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id'); } else { result = inverseRecord.createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { this._belongsToRelationships[keyName] = result; } return result; }, /** Returns the current value of a hasMany relationship. `hasMany` takes an optional hash of options as a second parameter, currently supported options are: - `ids`: set to `true` if you only want the IDs of the related records to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] // store.push('post', { id: 1, title: 'Hello World' }); postSnapshot.hasMany('comments'); // => undefined ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {(Array|undefined)} An array of snapshots or IDs of a known relationship or an empty array if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ hasMany: function (keyName, options) { var ids = options && options.ids; var relationship, members, hasData; var results; 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.Error('Model \'' + Ember.inspect(this.record) + '\' has no hasMany relationship named \'' + keyName + '\' defined.'); } hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData'); members = ember$data$lib$system$snapshot$$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; }, /** Iterates through all the attributes of the model, calling the passed function on each attribute. Example ```javascript snapshot.eachAttribute(function(name, meta) { // ... }); ``` @method eachAttribute @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachAttribute: function (callback, binding) { this.record.eachAttribute(callback, binding); }, /** Iterates through all the relationships of the model, calling the passed function on each relationship. Example ```javascript snapshot.eachRelationship(function(name, relationship) { // ... }); ``` @method eachRelationship @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { this.record.eachRelationship(callback, binding); }, /** @method get @param {String} keyName @return {Object} The property value @deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead */ get: function (keyName) { Ember.deprecate('Using DS.Snapshot.get() is deprecated. Use .attr(), .belongsTo() or .hasMany() instead.', false, { id: 'ds.snapshot.get-deprecated', until: '2.0.0' }); if (keyName === 'id') { return this.id; } if (keyName in this._attributes) { return this.attr(keyName); } var relationship = this._internalModel._relationships.get(keyName); if (relationship && relationship.relationshipMeta.kind === 'belongsTo') { return this.belongsTo(keyName); } if (relationship && relationship.relationshipMeta.kind === 'hasMany') { return this.hasMany(keyName); } return ember$data$lib$system$snapshot$$get(this.record, keyName); }, /** @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this.record.store.serializerFor(this.modelName).serialize(this, options); }, /** @method unknownProperty @param {String} keyName @return {Object} The property value @deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead */ unknownProperty: function (keyName) { return this.get(keyName); }, /** @method _createSnapshot @private */ _createSnapshot: function () { Ember.deprecate('You called _createSnapshot on what\'s already a DS.Snapshot. You shouldn\'t manually create snapshots in your adapter since the store passes snapshots to adapters by default.', false, { id: 'ds.snapshot.create-snapshot-on-snapshot', until: '2.0.0' }); return this; } }; Ember.defineProperty(ember$data$lib$system$snapshot$$Snapshot.prototype, 'typeKey', { enumerable: false, get: function () { Ember.deprecate('Snapshot.typeKey is deprecated. Use snapshot.modelName instead.', false, { id: 'ds.snapshot.type-key-deprecated', until: '2.0.0' }); return this.modelName; }, set: function () { Ember.assert('Setting snapshot.typeKey is not supported. In addition, Snapshot.typeKey has been deprecated for Snapshot.modelName.'); } }); var ember$data$lib$system$snapshot$$default = ember$data$lib$system$snapshot$$Snapshot; var ember$data$lib$system$model$internal$model$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$model$internal$model$$get = Ember.get; var ember$data$lib$system$model$internal$model$$set = Ember.set; var ember$data$lib$system$model$internal$model$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$model$internal$model$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$model$internal$model$$_extractPivotNameCache = ember$data$lib$system$object$polyfills$$create(null); var ember$data$lib$system$model$internal$model$$_splitOnDotCache = ember$data$lib$system$object$polyfills$$create(null); function ember$data$lib$system$model$internal$model$$splitOnDot(name) { return ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] || (ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] = name.split(".")); } function ember$data$lib$system$model$internal$model$$extractPivotName(name) { return ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] || (ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] = ember$data$lib$system$model$internal$model$$splitOnDot(name)[0]); } function ember$data$lib$system$model$internal$model$$retrieveFromCurrentState(key) { return function () { return ember$data$lib$system$model$internal$model$$get(this.currentState, key); }; } /** `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. @class InternalModel */ var ember$data$lib$system$model$internal$model$$InternalModel = function InternalModel(type, id, store, container, data) { this.type = type; this.id = id; this.store = store; this.container = container; this._data = data || ember$data$lib$system$object$polyfills$$create(null); this.modelName = type.modelName; this.dataHasInitialized = false; //Look into making this lazy this._deferredTriggers = []; this._attributes = ember$data$lib$system$object$polyfills$$create(null); this._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); this._relationships = new ember$data$lib$system$relationships$state$create$$default(this); this.currentState = ember$data$lib$system$model$states$$default.empty; this.isReloading = false; this.isError = false; this.error = null; /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr() }) ``` but there is also ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = ember$data$lib$system$object$polyfills$$create(null); }; ember$data$lib$system$model$internal$model$$InternalModel.prototype = { isEmpty: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isEmpty"), isLoading: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoading"), isLoaded: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoaded"), hasDirtyAttributes: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("hasDirtyAttributes"), isSaving: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isSaving"), isDeleted: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isDeleted"), isNew: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isNew"), isValid: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isValid"), dirtyType: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("dirtyType"), constructor: ember$data$lib$system$model$internal$model$$InternalModel, materializeRecord: function () { Ember.assert("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined); // lookupFactory should really return an object that creates // instances with the injections applied this.record = this.type._create({ id: this.id, store: this.store, container: this.container, _internalModel: this, currentState: ember$data$lib$system$model$internal$model$$get(this, "currentState"), isError: this.isError, adapterError: this.error }); this._triggerDeferredTriggers(); }, recordObjectWillDestroy: function () { this.record = null; }, deleteRecord: function () { this.send("deleteRecord"); }, save: function (options) { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; }, startedReloading: function () { this.isReloading = true; if (this.record) { ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", true); } }, finishedReloading: function () { this.isReloading = false; if (this.record) { ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", false); } }, reload: function () { this.startedReloading(); var record = this; var promiseLabel = "DS: Model#reload of " + this; return new ember$data$lib$system$model$internal$model$$Promise(function (resolve) { record.send("reloadRecord", resolve); }, promiseLabel).then(function () { record.didCleanError(); return record; }, function (error) { record.didError(error); throw error; }, "DS: Model#reload complete, update flags")["finally"](function () { record.finishedReloading(); record.updateRecordArrays(); }); }, getRecord: function () { if (!this.record) { this.materializeRecord(); } return this.record; }, unloadRecord: function () { this.send("unloadRecord"); }, eachRelationship: function (callback, binding) { return this.type.eachRelationship(callback, binding); }, eachAttribute: function (callback, binding) { return this.type.eachAttribute(callback, binding); }, inverseFor: function (key) { return this.type.inverseFor(key); }, setupData: function (data) { var changedKeys = this._changedKeys(data.attributes); ember$data$lib$system$merge$$default(this._data, data.attributes); this.pushedData(); if (this.record) { this.record._notifyProperties(changedKeys); } this.didInitalizeData(); }, becameReady: function () { Ember.run.schedule("actions", this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); }, didInitalizeData: function () { if (!this.dataHasInitialized) { this.becameReady(); this.dataHasInitialized = true; } }, destroy: function () { if (this.record) { return this.record.destroy(); } }, /** @method createSnapshot @private */ createSnapshot: function (options) { var adapterOptions = options && options.adapterOptions; var snapshot = new ember$data$lib$system$snapshot$$default(this); snapshot.adapterOptions = adapterOptions; return snapshot; }, /** @method loadingData @private @param {Promise} promise */ loadingData: function (promise) { this.send("loadingData", promise); }, /** @method loadedData @private */ loadedData: function () { this.send("loadedData"); this.didInitalizeData(); }, /** @method notFound @private */ notFound: function () { this.send("notFound"); }, /** @method pushedData @private */ pushedData: function () { this.send("pushedData"); }, flushChangedAttributes: function () { this._inFlightAttributes = this._attributes; this._attributes = ember$data$lib$system$object$polyfills$$create(null); }, /** @method adapterWillCommit @private */ adapterWillCommit: function () { this.send("willCommit"); }, /** @method adapterDidDirty @private */ adapterDidDirty: function () { this.send("becomeDirty"); this.updateRecordArraysLater(); }, /** @method send @private @param {String} name @param {Object} context */ send: function (name, context) { var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState"); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, notifyHasManyAdded: function (key, record, idx) { if (this.record) { this.record.notifyHasManyAdded(key, record, idx); } }, notifyHasManyRemoved: function (key, record, idx) { if (this.record) { this.record.notifyHasManyRemoved(key, record, idx); } }, notifyBelongsToChanged: function (key, record) { if (this.record) { this.record.notifyBelongsToChanged(key, record); } }, notifyPropertyChange: function (key) { if (this.record) { this.record.notifyPropertyChange(key); } }, rollbackAttributes: function () { var dirtyKeys = ember$data$lib$system$object$polyfills$$keysFunc(this._attributes); this._attributes = ember$data$lib$system$object$polyfills$$create(null); if (ember$data$lib$system$model$internal$model$$get(this, "isError")) { this._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); this.didCleanError(); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (this.isDeleted()) { //TODO: Should probably move this to the state machine somehow this.becameReady(); this.reconnectRelationships(); } if (this.isNew()) { this.clearRelationships(); } if (this.isValid()) { this._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); } this.send("rolledBack"); this.record._notifyProperties(dirtyKeys); }, /** @method transitionTo @private @param {String} name */ transitionTo: function (name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = ember$data$lib$system$model$internal$model$$extractPivotName(name); var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState"); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = ember$data$lib$system$model$internal$model$$splitOnDot(name); var setups = []; var enters = []; var i, l; 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); } } for (i = 0, l = enters.length; i < l; i++) { enters[i].enter(this); } ember$data$lib$system$model$internal$model$$set(this, "currentState", state); //TODO Consider whether this is the best approach for keeping these two in sync if (this.record) { ember$data$lib$system$model$internal$model$$set(this.record, "currentState", state); } for (i = 0, l = setups.length; i < l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function (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 " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, triggerLater: function () { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } Ember.run.scheduleOnce("actions", this, "_triggerDeferredTriggers"); }, _triggerDeferredTriggers: function () { //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.record) { return; } for (var i = 0, l = this._deferredTriggers.length; i < l; i++) { this.record.trigger.apply(this.record, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, /** @method clearRelationships @private */ clearRelationships: function () { this.eachRelationship(function (name, relationship) { if (this._relationships.has(name)) { var rel = this._relationships.get(name); //TODO(Igor) figure out whether we want to clear or disconnect rel.clear(); rel.destroy(); } }, this); var model = this; ember$data$lib$system$model$internal$model$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(this._implicitRelationships), function (key) { model._implicitRelationships[key].clear(); model._implicitRelationships[key].destroy(); }); }, disconnectRelationships: function () { this.eachRelationship(function (name, relationship) { this._relationships.get(name).disconnect(); }, this); var model = this; ember$data$lib$system$model$internal$model$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(this._implicitRelationships), function (key) { model._implicitRelationships[key].disconnect(); }); }, reconnectRelationships: function () { this.eachRelationship(function (name, relationship) { this._relationships.get(name).reconnect(); }, this); var model = this; ember$data$lib$system$model$internal$model$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(this._implicitRelationships), function (key) { model._implicitRelationships[key].reconnect(); }); }, /** When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.find('comment', 2, {post:1})` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function (preload) { var record = this; //TODO(Igor) consider the polymorphic case ember$data$lib$system$model$internal$model$$forEach.call(ember$data$lib$system$object$polyfills$$keysFunc(preload), function (key) { var preloadValue = ember$data$lib$system$model$internal$model$$get(preload, key); var relationshipMeta = record.type.metaForProperty(key); if (relationshipMeta.isRelationship) { record._preloadRelationship(key, preloadValue); } else { record._data[key] = preloadValue; } }); }, _preloadRelationship: function (key, preloadValue) { var relationshipMeta = this.type.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === "hasMany") { this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function (key, preloadValue, type) { Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue)); var internalModel = this; var recordsToSet = ember$data$lib$system$model$internal$model$$map.call(preloadValue, function (recordToPush) { return internalModel._convertStringOrNumberIntoInternalModel(recordToPush, type); }); //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).updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function (key, preloadValue, type) { var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type); //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).setRecord(recordToSet); }, _convertStringOrNumberIntoInternalModel: function (value, type) { if (typeof value === "string" || typeof value === "number") { return this.store._internalModelForId(type, value); } if (value._internalModel) { return value._internalModel; } return value; }, /** @method updateRecordArrays @private */ updateRecordArrays: function () { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.type, this); }, setId: function (id) { this.id = id; //TODO figure out whether maybe we should proxy ember$data$lib$system$model$internal$model$$set(this.record, "id", id); }, didError: function (error) { this.error = error; this.isError = true; if (this.record) { this.record.setProperties({ isError: true, adapterError: error }); } }, didCleanError: function () { this.error = null; this.isError = false; if (this.record) { this.record.setProperties({ isError: false, adapterError: null }); } }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function (data) { if (data) { data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); ember$data$lib$system$merge$$default(this._data, this._inFlightAttributes); if (data) { ember$data$lib$system$merge$$default(this._data, data); } this._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); this.send("didCommit"); this.updateRecordArraysLater(); if (!data) { return; } this.record._notifyProperties(changedKeys); }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function () { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule("actions", this, this.updateRecordArrays); }, addErrorMessageToAttribute: function (attribute, message) { var record = this.getRecord(); ember$data$lib$system$model$internal$model$$get(record, "errors").add(attribute, message); }, removeErrorMessageFromAttribute: function (attribute) { var record = this.getRecord(); ember$data$lib$system$model$internal$model$$get(record, "errors").remove(attribute); }, clearErrorMessages: function () { var record = this.getRecord(); ember$data$lib$system$model$internal$model$$get(record, "errors").clear(); }, // FOR USE DURING COMMIT PROCESS /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function (errors) { var attribute; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this._saveWasRejected(); }, /** @method adapterDidError @private */ adapterDidError: function (error) { this.send("becameError"); this.didError(error); this._saveWasRejected(); }, _saveWasRejected: function () { var keys = ember$data$lib$system$object$polyfills$$keysFunc(this._inFlightAttributes); for (var i = 0; i < keys.length; i++) { if (this._attributes[keys[i]] === undefined) { this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = ember$data$lib$system$object$polyfills$$create(null); }, /** Ember Data has 3 buckets for storing the value of an attribute on an internalModel. `_data` holds all of the attributes that have been acknowledged by a backend via the adapter. When rollbackAttributes is called on a model all attributes will revert to the record's state in `_data`. `_attributes` holds any change the user has made to an attribute that has not been acknowledged by the adapter. Any values in `_attributes` are have priority over values in `_data`. `_inFlightAttributes`. When a record is being synced with the backend the values in `_attributes` are copied to `_inFlightAttributes`. This way if the backend acknowledges the save but does not return the new state Ember Data can copy the values from `_inFlightAttributes` to `_data`. Without having to worry about changes made to `_attributes` while the save was happenign. Changed keys builds a list of all of the values that may have been changed by the backend after a successful save. It does this by iterating over each key, value pair in the payload returned from the server after a save. If the `key` is found in `_attributes` then the user has a local changed to the attribute that has not been synced with the server and the key is not included in the list of changed keys. If the value, for a key differs from the value in what Ember Data believes to be the truth about the backend state (A merger of the `_data` and `_inFlightAttributes` objects where `_inFlightAttributes` has priority) then that means the backend has updated the value and the key is added to the list of changed keys. @method _changedKeys @private */ _changedKeys: function (updates) { var changedKeys = []; if (updates) { var original, i, value, key; var keys = ember$data$lib$system$object$polyfills$$keysFunc(updates); var length = keys.length; original = ember$data$lib$system$merge$$default(ember$data$lib$system$object$polyfills$$create(null), this._data); original = ember$data$lib$system$merge$$default(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 (this._attributes[key] !== undefined) { continue; } if (!Ember.isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; }, toString: function () { if (this.record) { return this.record.toString(); } else { return "<" + this.modelName + ":" + this.id + ">"; } } }; var ember$data$lib$system$model$internal$model$$default = ember$data$lib$system$model$internal$model$$InternalModel; var ember$data$lib$system$store$$Backburner = Ember._Backburner || Ember.Backburner || Ember.__loader.require("backburner")["default"] || Ember.__loader.require("backburner")["Backburner"]; //Shim Backburner.join if (!ember$data$lib$system$store$$Backburner.prototype.join) { var ember$data$lib$system$store$$isString = function (suspect) { return typeof suspect === "string"; }; ember$data$lib$system$store$$Backburner.prototype.join = function () { var method, target; if (this.currentInstance) { var length = arguments.length; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (ember$data$lib$system$store$$isString(method)) { method = target[method]; } if (length === 1) { return method(); } else if (length === 2) { return method.call(target); } else { var args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } return method.apply(target, args); } } else { return this.run.apply(this, arguments); } }; } //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 ember$data$lib$system$store$$promiseRecord(internalModel, label) { var toReturn = internalModel.then(function (model) { return model.getRecord(); }); return ember$data$lib$system$promise$proxies$$promiseObject(toReturn, label); } var ember$data$lib$system$store$$get = Ember.get; var ember$data$lib$system$store$$set = Ember.set; var ember$data$lib$system$store$$once = Ember.run.once; var ember$data$lib$system$store$$isNone = Ember.isNone; var ember$data$lib$system$store$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$system$store$$indexOf = Ember.ArrayPolyfills.indexOf; var ember$data$lib$system$store$$map = Ember.ArrayPolyfills.map; var ember$data$lib$system$store$$Promise = Ember.RSVP.Promise; var ember$data$lib$system$store$$copy = Ember.copy; var ember$data$lib$system$store$$Store; var ember$data$lib$system$store$$Service = Ember.Service; if (!ember$data$lib$system$store$$Service) { ember$data$lib$system$store$$Service = Ember.Object; } // 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/stores/application.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 `find()` method: ```javascript store.find('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()`, `store#findAll()` or `store#filter()`. 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 */ ember$data$lib$system$store$$Store = ember$data$lib$system$store$$Service.extend({ /** @method init @private */ init: function () { this._backburner = new ember$data$lib$system$store$$Backburner(["normalizeRelationships", "syncRelationships", "finished"]); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = ember$data$lib$system$record$array$manager$$default.create({ store: this }); this._pendingSave = []; this._instanceCache = new ember$data$lib$system$store$container$instance$cache$$default(this.container); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = ember$data$lib$system$map$$Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `app/adapters/custom.js` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {(DS.Adapter|String)} */ adapter: "-rest", /** 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 @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function (record, options) { 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: Ember.computed("adapter", function () { var adapter = ember$data$lib$system$store$$get(this, "adapter"); Ember.assert("You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name", typeof adapter === "string"); adapter = this.retrieveManagedInstance("adapter", adapter); return 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 var 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) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); var properties = ember$data$lib$system$store$$copy(inputProperties) || ember$data$lib$system$object$polyfills$$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 (ember$data$lib$system$store$$isNone(properties.id)) { properties.id = this._generateId(modelName, properties); } // Coerce ID to a string properties.id = ember$data$lib$system$coerce$id$$default(properties.id); var internalModel = this.buildInternalModel(typeClass, properties.id); var record = internalModel.getRecord(); // Move the record out of its initial `empty` state into // the `loaded` state. internalModel.loadedData(); // Set the properties specified on the record. record.setProperties(properties); internalModel.eachRelationship(function (key, descriptor) { 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 var 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. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function (record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- You can optionally `preload` specific attributes and relationships that you know of by passing them as the third argument to find. 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 `find` call: ```javascript store.find('comment', 2, { preload: { post: 1 } }); ``` If you have access to the post model you can also pass the model itself: ```javascript store.find('post', 1).then(function (myPostModel) { store.find('comment', 2, {post: myPostModel}); }); ``` This way, your adapter's `find` or `buildURL` method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post. --- To find all records for a type, call `findAll`: ```javascript store.findAll('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. The promise will resolve into all records of this type present in the store, even if the server only returns a subset of them. @method find @param {String} modelName @param {(Object|String|Integer|null)} id @param {Object} options @return {Promise} promise */ find: function (modelName, id, preload) { Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1); Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id)); Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); if (arguments.length === 1) { Ember.deprecate("Using store.find(type) has been deprecated. Use store.findAll(type) to retrieve all records for a given type.", false, { id: "ds.store.find-with-type-deprecated", until: "2.0.0" }); return this.findAll(modelName); } // We are passed a query instead of an id. if (Ember.typeOf(id) === "object") { Ember.deprecate("Calling store.find() with a query object is deprecated. Use store.query() instead.", false, { id: "ds.store.find-with-type-deprecated", until: "2.0.0" }); return this.query(modelName, id); } var options = ember$data$lib$system$store$$deprecatePreload(preload, this.modelFor(modelName), "find"); return this.findRecord(modelName, ember$data$lib$system$coerce$id$$default(id), options); }, /** This method returns a fresh record for a given type and id combination. @method fetchById @deprecated Use [findRecord](#method_findRecord) instead @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ fetchById: function (modelName, id, preload) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var options = ember$data$lib$system$store$$deprecatePreload(preload, this.modelFor(modelName), "fetchById"); Ember.deprecate("Using store.fetchById(type, id) has been deprecated. Use store.findRecord(type, id, { reload: true }) to reload a record for a given type.", false, { id: "ds.store.fetch-by-id-deprecated", until: "2.0.0" }); if (this.hasRecordForId(modelName, id)) { return this.peekRecord(modelName, id).reload(); } else { return this.findRecord(modelName, id, options); } }, /** This method returns a fresh collection from the server, regardless of if there is already records in the store or not. @method fetchAll @deprecated Use [findAll](#method_findAll) instead @param {String} modelName @return {Promise} promise */ fetchAll: function (modelName) { Ember.deprecate("Using store.fetchAll(type) has been deprecated. Use store.findAll(type, { reload: true }) to retrieve all records for a given type.", false, { id: "ds.store.fetch-all-deprecated", until: "2.0.0" }); return this.findAll(modelName, { reload: true }); }, /** @method fetch @param {String} modelName @param {(String|Integer)} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise @deprecated Use [findRecord](#method_findRecord) instead */ fetch: function (modelName, id, preload) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); Ember.deprecate("Using store.fetch() has been deprecated. Use store.findRecord for fetching individual records or store.findAll for collections", false, { id: "ds.store.fetch-deprecated", until: "2.0.0" }); return this.findRecord(modelName, id, { reload: true, preload: preload }); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findById: function (modelName, id, preload) { Ember.deprecate("Using store.findById() has been deprecated. Use store.findRecord() to return a record for a given type and id combination.", false, { id: "ds.store.find-by-id-deprecated", until: "2.0.0" }); var options = ember$data$lib$system$store$$deprecatePreload(preload, this.modelFor(modelName), "findById"); return this.findRecord(modelName, id, options); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` If you would like to force the record to reload, instead of loading it from the cache when present you can set `reload: true` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { reload: true }); } }); ``` @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function (modelName, id, options) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var internalModel = this._internalModelForId(modelName, id); options = options || {}; if (!this.hasRecordForId(modelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return ember$data$lib$system$store$$promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + ember$data$lib$system$store$$get(internalModel, "id")); }, _findRecord: function (internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this.scheduleFetch(internalModel, options); } // Refetch the record if the adapter thinks the record is stale var snapshot = internalModel.createSnapshot(); snapshot.adapterOptions = options && options.adapterOptions; var typeClass = internalModel.type; var adapter = this.adapterFor(typeClass.modelName); if (adapter.shouldReloadRecord(this, snapshot)) { return this.scheduleFetch(internalModel, options); } // Trigger the background refetch if all the previous checks fail if (adapter.shouldBackgroundReloadRecord(this, snapshot)) { this.scheduleFetch(internalModel, options); } // Return the cached record return ember$data$lib$system$store$$Promise.resolve(internalModel); }, _findByInternalModel: function (internalModel, options) { options = options || {}; if (options.preload) { internalModel._preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return ember$data$lib$system$store$$promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + ember$data$lib$system$store$$get(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 ember$data$lib$system$store$$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) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var store = this; return ember$data$lib$system$promise$proxies$$promiseArray(Ember.RSVP.all(ember$data$lib$system$store$$map.call(ids, function (id) { return store.findRecord(modelName, id); })).then(Ember.A, null, "DS: Store#findByIds of " + modelName + " 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 */ // TODO rename this to have an underscore fetchRecord: function (internalModel, options) { var typeClass = internalModel.type; var id = internalModel.id; var adapter = this.adapterFor(typeClass.modelName); Ember.assert("You tried to find a record but you have no adapter (for " + typeClass + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + typeClass + ") does not implement 'findRecord'", typeof adapter.findRecord === "function" || typeof adapter.find === "function"); var promise = ember$data$lib$system$store$finders$$_find(adapter, this, typeClass, id, internalModel, options); return promise; }, scheduleFetchMany: function (records) { var internalModels = ember$data$lib$system$store$$map.call(records, function (record) { return record._internalModel; }); return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map.call(internalModels, this.scheduleFetch, this)); }, scheduleFetch: function (internalModel, options) { var typeClass = internalModel.type; if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var resolver = Ember.RSVP.defer("Fetching " + typeClass + "with id: " + internalModel.id); var pendingFetchItem = { record: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); if (!this._pendingFetch.get(typeClass)) { this._pendingFetch.set(typeClass, [pendingFetchItem]); } else { this._pendingFetch.get(typeClass).push(pendingFetchItem); } Ember.run.scheduleOnce("afterRender", this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function () { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = ember$data$lib$system$map$$Map.create(); }, _flushPendingFetchForType: function (pendingFetchItems, typeClass) { var store = this; var adapter = store.adapterFor(typeClass.modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = Ember.A(pendingFetchItems).mapBy("record"); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record, recordResolverPair.options)); // TODO adapter options } function resolveFoundRecords(records) { ember$data$lib$system$store$$forEach.call(records, function (record) { var pair = Ember.A(pendingFetchItems).findBy("record", record); if (pair) { var resolver = pair.resolver; resolver.resolve(record); } }); return records; } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { resolvedRecords = Ember.A(resolvedRecords); var missingRecords = requestedRecords.reject(function (record) { return resolvedRecords.contains(record); }); if (missingRecords.length) { Ember.warn("Ember Data expected to find records with the following ids in the adapter response but they were missing: " + Ember.inspect(Ember.A(missingRecords).mapBy("id")), false, { id: "ds.store.missing-records-from-adapter" }); } rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { ember$data$lib$system$store$$forEach.call(records, function (record) { var pair = Ember.A(pendingFetchItems).findBy("record", record); if (pair) { var resolver = pair.resolver; resolver.reject(error); } }); } if (pendingFetchItems.length === 1) { _fetchRecord(pendingFetchItems[0]); } else 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 = Ember.A(records).invoke("createSnapshot"); var groups = adapter.groupRecordsForFindMany(this, snapshots); ember$data$lib$system$store$$forEach.call(groups, function (groupOfSnapshots) { var groupOfRecords = Ember.A(groupOfSnapshots).mapBy("_internalModel"); var requestedRecords = Ember.A(groupOfRecords); var ids = requestedRecords.mapBy("id"); if (ids.length > 1) { ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = Ember.A(pendingFetchItems).findBy("record", groupOfRecords[0]); _fetchRecord(pair); } else { Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { ember$data$lib$system$store$$forEach.call(pendingFetchItems, _fetchRecord); } }, /** 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. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.getById('post', 1); post.get('id'); // 1 ``` @method getById @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ getById: function (modelName, id) { Ember.deprecate("Using store.getById() has been deprecated. Use store.peekRecord to get a record by a given type and ID without triggering a fetch.", false, { id: "ds.store.get-by-id-deprecated", until: "2.0.0" }); return this.peekRecord(modelName, id); }, /** 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. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function (modelName, id) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); if (this.hasRecordForId(modelName, id)) { return this._internalModelForId(modelName, 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 modelName = internalModel.type.modelName; var adapter = this.adapterFor(modelName); var id = internalModel.id; Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + modelName + ")", adapter); Ember.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); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {(String|DS.Model)} modelName @param {(String|Integer)} inputId @return {Boolean} */ hasRecordForId: function (modelName, inputId) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); var id = ember$data$lib$system$coerce$id$$default(inputId); var internalModel = this.typeMapFor(typeClass).idToRecord[id]; 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) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function (typeName, inputId) { var typeClass = this.modelFor(typeName); var id = ember$data$lib$system$coerce$id$$default(inputId); var idToRecord = this.typeMapFor(typeClass).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildInternalModel(typeClass, id); } return record; }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function (internalModels) { var store = this; return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map.call(internalModels, function (internalModel) { return store._findByInternalModel(internalModel); })); }, /** 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 {DS.Model} owner @param {any} link @param {(Relationship)} relationship @return {Promise} promise */ findHasMany: function (owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.type + ")", adapter); Ember.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 ember$data$lib$system$store$finders$$_findHasMany(adapter, this, owner, link, relationship); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function (owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.type + ")", adapter); Ember.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 ember$data$lib$system$store$finders$$_findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. 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 a `RecordArray` once the server returns. @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function (modelName, query) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); var array = this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query); var adapter = this.adapterFor(modelName); Ember.assert("You tried to load a query but you have no adapter (for " + typeClass + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `query`", typeof adapter.query === "function" || typeof adapter.findQuery === "function"); return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_query(adapter, this, typeClass, query, array)); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. 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. This method returns a promise, which is resolved with a `RecordObject` once the server returns. @method queryRecord @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ queryRecord: function (modelName, query) { Ember.assert("You need to pass a type to the store's queryRecord method", modelName); Ember.assert("You need to pass a query hash to the store's queryRecord method", query); Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); var adapter = this.adapterFor(modelName); Ember.assert("You tried to make a query but you have no adapter (for " + typeClass + ")", adapter); Ember.assert("You tried to make a query but your adapter does not implement `queryRecord`", typeof adapter.queryRecord === "function"); return ember$data$lib$system$promise$proxies$$promiseObject(ember$data$lib$system$store$finders$$_queryRecord(adapter, this, typeClass, query)); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. 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. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise @deprecated Use `store.query instead` */ findQuery: function (modelName, query) { Ember.deprecate("store#findQuery is deprecated. You should use store#query instead.", false, { id: "ds.store.find-query-deprecated", until: "2.0.0" }); return this.query(modelName, query); }, /** `findAll` ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. The promise will resolve into all records of this type present in the store, even if the server only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('author'); } }); ``` @method findAll @param {String} modelName @param {Object} options @return {DS.AdapterPopulatedRecordArray} */ findAll: function (modelName, options) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); return this._fetchAll(typeClass, this.peekAll(modelName), options); }, /** @method _fetchAll @private @param {DS.Model} typeClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function (typeClass, array, options) { options = options || {}; var adapter = this.adapterFor(typeClass.modelName); var sinceToken = this.typeMapFor(typeClass).metadata.since; ember$data$lib$system$store$$set(array, "isUpdating", true); Ember.assert("You tried to load all records but you have no adapter (for " + typeClass + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === "function"); if (options.reload) { return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken, options)); } var snapshotArray = array.createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken, options)); } if (adapter.shouldBackgroundReloadAll(this, snapshotArray)) { ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken, options)); } return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$$Promise.resolve(array)); }, /** @method didUpdateAll @param {DS.Model} typeClass @private */ didUpdateAll: function (typeClass) { var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); ember$data$lib$system$store$$set(liveRecordArray, "isUpdating", false); }, /** 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.find](#method_find). Also note that multiple calls to `all` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.all('post'); ``` @method all @param {String} modelName @return {DS.RecordArray} */ all: function (modelName) { Ember.deprecate("Using store.all() has been deprecated. Use store.peekAll() to get all records by a given type without triggering a fetch.", false, { id: "ds.store.all-renamed-deprecated", until: "2.0.0" }); return this.peekAll(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.find](#method_find). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.peekAll('post'); ``` @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function (modelName) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); this.recordArrayManager.populateLiveRecordArray(liveRecordArray, typeClass); return liveRecordArray; }, /** This method unloads all records in the store. 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) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), !modelName || typeof modelName === "string"); if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = ember$data$lib$system$object$polyfills$$keysFunc(typeMaps); var types = ember$data$lib$system$store$$map.call(keys, byType); ember$data$lib$system$store$$forEach.call(types, this.unloadAll, this); } else { var typeClass = this.modelFor(modelName); var typeMap = this.typeMapFor(typeClass); var records = typeMap.records.slice(); var record; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.metadata = ember$data$lib$system$object$polyfills$$create(null); } function byType(entry) { return typeMaps[entry]["type"].modelName; } }, /** 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 [find](#method_find) 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 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function (modelName, query, filter) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); if (!Ember.ENV.ENABLE_DS_FILTER) { Ember.deprecate("The filter API will be moved into a plugin soon. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page", false, { url: "https://github.com/ember-data/ember-data-filter", id: "ds.store.filter-deprecated", until: "2.0.0" }); } var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.query(modelName, query); } else if (arguments.length === 2) { filter = query; } modelName = this.modelFor(modelName); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter); } promise = promise || ember$data$lib$system$store$$Promise.cast(array); return ember$data$lib$system$promise$proxies$$promiseArray(promise.then(function () { return array; }, null, "DS: Store#filter of " + modelName)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.find('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function (modelName, id) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); return this.hasRecordForId(modelName, id); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String} modelName @return {object} @deprecated */ metadataFor: function (modelName) { Ember.deprecate("`store.metadataFor()` has been deprecated. You can use `.get('meta')` on relationships and arrays returned from `store.query()`.", false, { id: "ds.store.metadata-for-deprecated", until: "2.0.0" }); return this._metadataFor(modelName); }, /** @method _metadataFor @param {String} modelName @return {object} @private */ _metadataFor: function (modelName) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); return this.typeMapFor(typeClass).metadata; }, /** This method sets the metadata for a specific type. @method setMetadataFor @param {String} modelName @param {Object} metadata metadata to set @return {object} @deprecated */ setMetadataFor: function (modelName, metadata) { Ember.deprecate("`store.setMetadataFor()` has been deprecated. Please return meta from your serializer's `extractMeta` hook.", false, { id: "ds.store.set-metadata-for-deprecated", until: "2.0.0" }); this._setMetadataFor(modelName, metadata); }, /** @method _setMetadataFor @param {String} modelName @param {Object} metadata metadata to set @private */ _setMetadataFor: function (modelName, metadata) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var typeClass = this.modelFor(modelName); Ember.merge(this.typeMapFor(typeClass).metadata, metadata); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {InternalModel} internalModel */ dataWasUpdated: function (type, internalModel) { this.recordArrayManager.recordDidChange(internalModel); }, // .............. // . 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 }); ember$data$lib$system$store$$once(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 = []; ember$data$lib$system$store$$forEach.call(pending, function (pendingItem) { var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var record = snapshot._internalModel; var adapter = this.adapterFor(record.type.modelName); var operation; if (ember$data$lib$system$store$$get(record, "currentState.stateName") === "root.deleted.saved") { return resolver.resolve(); } else if (record.isNew()) { operation = "createRecord"; } else if (record.isDeleted()) { operation = "deleteRecord"; } else { operation = "updateRecord"; } resolver.resolve(ember$data$lib$system$store$$_commit(adapter, this, operation, snapshot)); }, this); }, /** 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; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this._backburner.schedule("normalizeRelationships", this, "_setupRelationships", internalModel, internalModel.type, data); this.updateId(internalModel, data); } //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 id = ember$data$lib$system$coerce$id$$default(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + internalModel + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {DS.Model} typeClass @return {Object} typeMap */ typeMapFor: function (typeClass) { var typeMaps = ember$data$lib$system$store$$get(this, "typeMaps"); var guid = Ember.guidFor(typeClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: ember$data$lib$system$object$polyfills$$create(null), records: [], metadata: ember$data$lib$system$object$polyfills$$create(null), type: typeClass }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {(String|DS.Model)} type @param {Object} data */ _load: function (data) { var id = ember$data$lib$system$coerce$id$$default(data.id); var internalModel = this._internalModelForId(data.type, id); internalModel.setupData(data); this.recordArrayManager.recordDidChange(internalModel); return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` var Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); var 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 */ _modelForMixin: function (modelName) { var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName); var registry = this.container._registry ? this.container._registry : this.container; var mixin = registry.resolve("mixin:" + normalizedModelName); if (mixin) { //Cache the class as a model registry.register("model:" + normalizedModelName, DS.Model.extend(mixin)); } var factory = this.modelFactoryFor(normalizedModelName); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function (modelName) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new Ember.Error("No model was found for '" + modelName + "'"); } factory.modelName = factory.modelName || ember$data$lib$system$normalize$model$name$$default(modelName); // deprecate typeKey if (!("typeKey" in factory)) { Ember.defineProperty(factory, "typeKey", { enumerable: true, configurable: false, get: function () { Ember.deprecate("Usage of `typeKey` has been deprecated and will be removed in Ember Data 2.0. It has been replaced by `modelName` on the model class.", false, { id: "ds.model.type-key-replace-by-model-name", until: "2.0.0" }); var typeKey = this.modelName; if (typeKey) { typeKey = Ember.String.camelize(this.modelName); } return typeKey; }, set: function () { Ember.assert("Setting typeKey is not supported. In addition, typeKey has also been deprecated in favor of modelName. Setting modelName is also not supported."); } }); } return factory; }, modelFactoryFor: function (modelName) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var normalizedKey = ember$data$lib$system$normalize$model$name$$default(modelName); return this.container.lookupFactory("model:" + normalizedKey); }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/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('person', 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 {String} modelName @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function (modelNameArg, dataArg) { var _this = this; var data, modelName; if (Ember.typeOf(modelNameArg) === "object" && Ember.typeOf(dataArg) === "undefined") { data = modelNameArg; } else { Ember.deprecate("store.push(type, data) has been deprecated. Please provide a JSON-API document object as the first and only argument to store.push.", false, { id: "ds.store.push-with-type-and-data-deprecated", until: "2.0.0" }); Ember.assert("Expected an object as `data` in a call to `push` for " + modelNameArg + " , but was " + Ember.typeOf(dataArg), Ember.typeOf(dataArg) === "object"); Ember.assert("You must include an `id` for " + modelNameArg + " in an object passed to `push`", dataArg.id != null && dataArg.id !== ""); data = ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayload(this.modelFor(modelNameArg), dataArg); modelName = modelNameArg; Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string" || typeof data === "undefined"); } if (data.included) { ember$data$lib$system$store$$forEach.call(data.included, function (recordData) { return _this._pushInternalModel(recordData); }); } if (Ember.typeOf(data.data) === "array") { var internalModels = ember$data$lib$system$store$$map.call(data.data, function (recordData) { return _this._pushInternalModel(recordData); }); return ember$data$lib$system$store$$map.call(internalModels, function (internalModel) { return internalModel.getRecord(); }); } var internalModel = this._pushInternalModel(data.data || data); return internalModel.getRecord(); }, _hasModelFor: function (type) { return this.container.lookupFactory("model:" + type); }, _pushInternalModel: function (data) { var modelName = data.type; Ember.assert("Expected an object as 'data' in a call to 'push' for " + modelName + ", but was " + Ember.typeOf(data), Ember.typeOf(data) === "object"); Ember.assert("You must include an 'id' for " + modelName + " in an object passed to 'push'", data.id != null && data.id !== ""); Ember.assert("You tried to push data with a type '" + modelName + "' but no model could be found with that name.", this._hasModelFor(modelName)); var type = this.modelFor(modelName); var filter = Ember.ArrayPolyfills.filter; // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown keys, log a warning. if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) { Ember.warn("The payload for '" + type.modelName + "' contains these unknown keys: " + Ember.inspect(filter.call(ember$data$lib$system$object$polyfills$$keysFunc(data), function (key) { return !(key === "id" || key === "links" || ember$data$lib$system$store$$get(type, "fields").has(key) || key.match(/Type$/)); })) + ". Make sure they've been defined in your model.", filter.call(ember$data$lib$system$object$polyfills$$keysFunc(data), function (key) { return !(key === "id" || key === "links" || ember$data$lib$system$store$$get(type, "fields").has(key) || key.match(/Type$/)); }).length === 0, { id: "ds.store.unknown-keys-in-payload" }); } // Actually load the record into the store. var internalModel = this._load(data); var store = this; this._backburner.join(function () { store._backburner.schedule("normalizeRelationships", store, "_setupRelationships", internalModel, type, data); }); return internalModel; }, _setupRelationships: function (record, type, data) { // If the payload contains relationships that are specified as // IDs, normalizeRelationships will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the // store. data = ember$data$lib$system$store$$normalizeRelationships(this, type, data); // Now that the pushed record as well as any related records // are in the store, create the data structures used to track // relationships. ember$data$lib$system$store$$setupRelationships(this, record, data); }, /** 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 var 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. However, the serializer itself (processing this data via `normalizePayload`) will not know which model it is deserializing. ```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; var payload; if (!inputPayload) { payload = modelName; serializer = ember$data$lib$system$store$$defaultSerializer(this); Ember.assert("You cannot use `store#pushPayload` without a modelName unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === "function"); } else { payload = inputPayload; Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); serializer = this.serializerFor(modelName); } var store = this; this._adapterRun(function () { serializer.pushPayload(store, payload); }); }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(modelName, 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) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); var serializer = this.serializerFor(modelName); var model = this.modelFor(modelName); return serializer.normalize(model, payload); }, /** @method update @param {String} modelName @param {Object} data @return {DS.Model} the record that was updated. @deprecated Use [push](#method_push) instead */ update: function (modelName, data) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); Ember.deprecate("Using store.update() has been deprecated since store.push() now handles partial updates. You should use store.push() instead.", false, { id: "ds.store.update-deprecated", until: "2.0.0" }); return this.push(modelName, data); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String} modelName @param {Array} datas @return {Array} */ pushMany: function (modelName, datas) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); Ember.deprecate("Using store.pushMany() has been deprecated since store.push() now handles multiple items. You should use store.push() instead.", false, { id: "ds.store.push-many-deprecated", until: "2.0.0" }); var length = datas.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = this.push(modelName, datas[i]); } return result; }, /** @method metaForType @param {String} modelName @param {Object} metadata @deprecated Use [setMetadataFor](#method_setMetadataFor) instead */ metaForType: function (modelName, metadata) { Ember.assert("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), typeof modelName === "string"); Ember.deprecate("Using store.metaForType() has been deprecated. Use store.setMetadataFor() to set metadata for a specific type.", false, { id: "ds.store.meta-for-type-deprecated", until: "2.0.0" }); this.setMetadataFor(modelName, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {DS.Model} type @param {String} id @param {Object} data @return {InternalModel} internal model */ buildInternalModel: function (type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; Ember.assert("The id " + id + " has already been used with another record of type " + type.toString() + ".", !id || !idToRecord[id]); Ember.assert("`" + Ember.inspect(type) + "` does not appear to be an ember-data model", typeof type._create === "function"); // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new ember$data$lib$system$model$internal$model$$default(type, id, this, this.container, data); // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = internalModel; } typeMap.records.push(internalModel); return internalModel; }, //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 . // ............... /** @method dematerializeRecord @private @param {DS.Model} record @deprecated Use [unloadRecord](#method_unloadRecord) instead */ dematerializeRecord: function (record) { Ember.deprecate("Using store.dematerializeRecord() has been deprecated since it was intended for private use only. You should use store.unloadRecord() instead.", false, { id: "ds.store.dematerialize-record-deprecated", until: "2.0.0" }); this._dematerializeRecord(record); }, /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _dematerializeRecord @private @param {InternalModel} internalModel */ _dematerializeRecord: function (internalModel) { var type = internalModel.type; var typeMap = this.typeMapFor(type); var id = internalModel.id; internalModel.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = ember$data$lib$system$store$$indexOf.call(typeMap.records, internalModel); typeMap.records.splice(loc, 1); }, // ...................... // . 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 @private @param {String} modelName @return DS.Adapter */ adapterFor: function (modelOrClass) { var modelName; if (typeof modelOrClass === "string") { modelName = modelOrClass; } else { Ember.deprecate("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), false, { id: "ds.store.passing-classes-deprecated", until: "2.0.0" }); modelName = modelOrClass.modelName; } return this.lookupAdapter(modelName); }, _adapterRun: function (fn) { return this._backburner.run(fn); }, // .............................. // . 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 @private @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function (modelOrClass) { var modelName; if (typeof modelOrClass === "string") { modelName = modelOrClass; } else { Ember.deprecate("Passing classes to store methods has been removed. Please pass a dasherized string instead of " + Ember.inspect(modelName), false, { id: "ds.store.passing-classes-deprecated", until: "2.0.0" }); modelName = modelOrClass.modelName; } var fallbacks = ["application", this.adapterFor(modelName).get("defaultSerializer"), "-default"]; var serializer = this.lookupSerializer(modelName, fallbacks); return serializer; }, /** Retrieve a particular instance from the container cache. If not found, creates it and placing it in the cache. Enabled a store to manage local instances of adapters and serializers. @method retrieveManagedInstance @private @param {String} modelName the object modelName @param {String} name the object name @param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails @return {Ember.Object} */ retrieveManagedInstance: function (type, modelName, fallbacks) { var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName); var instance = this._instanceCache.get(type, normalizedModelName, fallbacks); ember$data$lib$system$store$$set(instance, "store", this); return instance; }, lookupAdapter: function (name) { return this.retrieveManagedInstance("adapter", name, this.get("_adapterFallbacks")); }, _adapterFallbacks: Ember.computed("adapter", function () { var adapter = this.get("adapter"); return ["application", adapter, "-rest"]; }), lookupSerializer: function (name, fallbacks) { return this.retrieveManagedInstance("serializer", name, fallbacks); }, willDestroy: function () { this.recordArrayManager.destroy(); this.unloadAll(); for (var cacheKey in this._containerCache) { this._containerCache[cacheKey].destroy(); delete this._containerCache[cacheKey]; } delete this._containerCache; } }); function ember$data$lib$system$store$$normalizeRelationships(store, type, data, record) { data.relationships = data.relationships || {}; type.eachRelationship(function (key, relationship) { var kind = relationship.kind; var value; if (data.relationships[key] && data.relationships[key].data) { value = data.relationships[key].data; if (kind === "belongsTo") { data.relationships[key].data = ember$data$lib$system$store$$deserializeRecordId(store, key, relationship, value); } else if (kind === "hasMany") { data.relationships[key].data = ember$data$lib$system$store$$deserializeRecordIds(store, key, relationship, value); } } }); return data; } function ember$data$lib$system$store$$deserializeRecordId(store, key, relationship, id) { if (ember$data$lib$system$store$$isNone(id)) { return; } Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being " + Ember.inspect(id) + ", but " + key + " is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.", !Ember.isArray(id)); //TODO:Better asserts return store._internalModelForId(id.type, id.id); } function ember$data$lib$system$store$$deserializeRecordIds(store, key, relationship, ids) { if (ember$data$lib$system$store$$isNone(ids)) { return; } Ember.assert("A " + relationship.parentType + " record was pushed into the store with the value of " + key + " being '" + Ember.inspect(ids) + "', but " + key + " is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.", Ember.isArray(ids)); return ember$data$lib$system$store$$map.call(ids, function (id) { return ember$data$lib$system$store$$deserializeRecordId(store, key, relationship, id); }); } // Delegation to the adapter and promise management function ember$data$lib$system$store$$defaultSerializer(store) { return store.serializerFor("application"); } function ember$data$lib$system$store$$_commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var typeClass = store.modelFor(modelName); var promise = adapter[operation](store, typeClass, snapshot); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName); var label = "DS: Extract and notify about " + operation + " completion of " + internalModel; Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !== undefined); promise = ember$data$lib$system$store$$Promise.cast(promise, label); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store)); promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload, data; if (adapterPayload) { payload = ember$data$lib$system$store$serializer$response$$normalizeResponseHelper(serializer, store, typeClass, adapterPayload, snapshot.id, operation); if (payload.included) { store.push({ data: payload.included }); } data = ember$data$lib$system$store$serializer$response$$convertResourceObject(payload.data); } store.didSaveRecord(internalModel, ember$data$lib$system$store$serializer$response$$_normalizeSerializerPayload(internalModel.type, data)); }); return internalModel; }, function (error) { if (error instanceof ember$data$lib$adapters$errors$$InvalidError) { var errors = serializer.extractErrors(store, typeClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function ember$data$lib$system$store$$setupRelationships(store, record, data) { var typeClass = record.type; if (!data.relationships) { return; } typeClass.eachRelationship(function (key, descriptor) { var kind = descriptor.kind; if (!data.relationships[key]) { return; } var relationship; if (data.relationships[key].links && data.relationships[key].links.related) { relationship = record._relationships.get(key); relationship.updateLink(data.relationships[key].links.related); } if (data.relationships[key].meta) { relationship = record._relationships.get(key); relationship.updateMeta(data.relationships[key].meta); } var value = data.relationships[key].data; if (value !== undefined) { if (kind === "belongsTo") { relationship = record._relationships.get(key); relationship.setCanonicalRecord(value); } else if (kind === "hasMany") { relationship = record._relationships.get(key); relationship.updateRecordsFromAdapter(value); } } }); } function ember$data$lib$system$store$$deprecatePreload(preloadOrOptions, type, methodName) { if (preloadOrOptions) { var modelProperties = []; var fields = Ember.get(type, "fields"); fields.forEach(function (fieldType, key) { modelProperties.push(key); }); var preloadDetected = false; for (var i = 0, _length = modelProperties.length; i < _length; i++) { var key = modelProperties[i]; if (typeof preloadOrOptions[key] !== "undefined") { preloadDetected = true; break; } } if (preloadDetected) { Ember.deprecate("Passing a preload argument to `store." + methodName + "` is deprecated. Please move it to the preload key on the " + methodName + " `options` argument.", false, { id: "ds.store.preload-outside-options", until: "2.0.0" }); var preload = preloadOrOptions; return { preload: preload }; } } return preloadOrOptions; } var ember$data$lib$system$store$$default = ember$data$lib$system$store$$Store; var ember$data$lib$serializers$json$api$serializer$$dasherize = Ember.String.dasherize; var ember$data$lib$serializers$json$api$serializer$$get = Ember.get; var ember$data$lib$serializers$json$api$serializer$$map = Ember.ArrayPolyfills.map; var ember$data$lib$serializers$json$api$serializer$$default = ember$data$lib$serializers$json$serializer$$default.extend({ /* This is only to be used temporarily during the transition from the old serializer API to the new one. `JSONAPISerializer` only supports the new Serializer API. @property isNewSerializerAPI */ isNewSerializerAPI: true, /* @method _normalizeDocumentHelper @param {Object} documentHash @return {Object} @private */ _normalizeDocumentHelper: function (documentHash) { if (Ember.typeOf(documentHash.data) === 'object') { documentHash.data = this._normalizeResourceHelper(documentHash.data); } else if (Ember.typeOf(documentHash.data) === 'array') { documentHash.data = ember$data$lib$serializers$json$api$serializer$$map.call(documentHash.data, this._normalizeResourceHelper, this); } if (Ember.typeOf(documentHash.included) === 'array') { documentHash.included = ember$data$lib$serializers$json$api$serializer$$map.call(documentHash.included, this._normalizeResourceHelper, this); } return documentHash; }, /* @method _normalizeRelationshipDataHelper @param {Object} relationshipDataHash @return {Object} @private */ _normalizeRelationshipDataHelper: function (relationshipDataHash) { var type = this.modelNameFromPayloadKey(relationshipDataHash.type); relationshipDataHash.type = type; return relationshipDataHash; }, /* @method _normalizeResourceHelper @param {Object} resourceHash @return {Object} @private */ _normalizeResourceHelper: function (resourceHash) { var modelName = this.modelNameFromPayloadKey(resourceHash.type); var modelClass = this.store.modelFor(modelName); var serializer = this.store.serializerFor(modelName); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$json$api$serializer$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + serializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$json$api$serializer$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$json$api$serializer$$get(serializer, 'isNewSerializerAPI')); var _serializer$normalize = serializer.normalize(modelClass, resourceHash); var data = _serializer$normalize.data; return data; }, /** @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function (store, payload) { var normalizedPayload = this._normalizeDocumentHelper(payload); store.push(normalizedPayload); }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var normalizedPayload = this._normalizeDocumentHelper(payload); return normalizedPayload; }, /* @method extractAttributes @param {DS.Model} modelClass @param {Object} resourceHash @return {Object} */ 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.hasOwnProperty(attributeKey)) { attributes[key] = resourceHash.attributes[attributeKey]; } }); } return attributes; }, /* @method extractRelationship @param {Object} relationshipHash @return {Object} */ extractRelationship: function (relationshipHash) { if (Ember.typeOf(relationshipHash.data) === 'object') { relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); } if (Ember.typeOf(relationshipHash.data) === 'array') { relationshipHash.data = ember$data$lib$serializers$json$api$serializer$$map.call(relationshipHash.data, this._normalizeRelationshipDataHelper, this); } return relationshipHash; }, /* @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ 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.hasOwnProperty(relationshipKey)) { var relationshipHash = resourceHash.relationships[relationshipKey]; relationships[key] = _this2.extractRelationship(relationshipHash); } }); } return relationships; }, /* @method extractType @param {DS.Model} modelClass @param {Object} resourceHash @return {String} @private */ _extractType: function (modelClass, resourceHash) { return this.modelNameFromPayloadKey(resourceHash.type); }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function (key) { return ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(key)); }, /** @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function (modelName) { return ember$inflector$lib$lib$system$string$$pluralize(modelName); }, /* @method normalize @param {DS.Model} modelClass @param {Object} resourceHash @return {String} */ normalize: function (modelClass, resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); 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` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys. This behaviour can be easily customized by extending this method. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.dasherize(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return ember$data$lib$serializers$json$api$serializer$$dasherize(key); }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties. This behaviour can be easily customized by extending this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForRelationship: function(key, relationship, method) { return Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return ember$data$lib$serializers$json$api$serializer$$dasherize(key); }, /** @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { var data = this._super.apply(this, arguments); data.type = this.payloadKeyFromModelName(snapshot.modelName); return { data: data }; }, /** @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ 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); } var payloadKey = this._getMappedKey(key); if (payloadKey === key) { payloadKey = this.keyForAttribute(key, 'serialize'); } json.attributes[payloadKey] = value; } }, /** @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ 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); if (payloadKey === key) { payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); } var data = null; if (belongsTo) { data = { type: this.payloadKeyFromModelName(belongsTo.modelName), id: belongsTo.id }; } json.relationships[payloadKey] = { data: data }; } } }, /** @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var _this3 = this; var key = relationship.key; if (this._shouldSerializeHasMany(snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key); if (hasMany !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); } var data = ember$data$lib$serializers$json$api$serializer$$map.call(hasMany, function (item) { return { type: _this3.payloadKeyFromModelName(item.modelName), id: item.id }; }); json.relationships[payloadKey] = { data: data }; } } } }); var ember$data$lib$initializers$store$$default = ember$data$lib$initializers$store$$initializeStore; /** Configures a registry for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Registry} registry @param {Object} [application] an application namespace */ function ember$data$lib$initializers$store$$initializeStore(registry, application) { Ember.deprecate("Specifying a custom Store for Ember Data on your global namespace as `App.Store` " + "has been deprecated. Please use `App.ApplicationStore` instead.", !(application && application.Store), { id: "ds.initializer.specifying-custom-store-on-global-namespace-deprecated", until: "2.0.0" }); registry.optionsForType("serializer", { singleton: false }); registry.optionsForType("adapter", { singleton: false }); // allow older names to be looked up var proxy = new ember$data$lib$system$container$proxy$$default(registry); proxy.registerDeprecations([{ deprecated: "serializer:_default", valid: "serializer:-default" }, { deprecated: "serializer:_rest", valid: "serializer:-rest" }, { deprecated: "adapter:_rest", valid: "adapter:-rest" }]); // new go forward paths registry.register("serializer:-default", ember$data$lib$serializers$json$serializer$$default.extend({ isNewSerializerAPI: true })); registry.register("serializer:-rest", ember$data$lib$serializers$rest$serializer$$default.extend({ isNewSerializerAPI: true })); registry.register("adapter:-rest", ember$data$lib$adapters$rest$adapter$$default); registry.register("adapter:-json-api", ember$data$lib$adapters$json$api$adapter$$default); registry.register("serializer:-json-api", ember$data$lib$serializers$json$api$serializer$$default); var store; if (registry.has("store:main")) { Ember.deprecate("Registering a custom store as `store:main` or defining a store in app/store.js has been deprecated. Please move you store to `service:store` or define your custom store in `app/services/store.js`", false, { id: "ds.initializer.custom-store-as-store-main-deprecated", until: "2.0.0" }); store = registry.lookup("store:main"); } else { var storeMainProxy = new ember$data$lib$system$container$proxy$$default(registry); storeMainProxy.registerDeprecations([{ deprecated: "store:main", valid: "service:store" }]); } if (registry.has("store:application")) { Ember.deprecate("Registering a custom store as `store:main` or defining a store in app/store.js has been deprecated. Please move you store to `service:store` or define your custom store in `app/services/store.js`", false, { id: "ds.initializer.custom-store-as-store-main-deprecated", until: "2.0.0" }); store = registry.lookup("store:application"); } else { var storeApplicationProxy = new ember$data$lib$system$container$proxy$$default(registry); storeApplicationProxy.registerDeprecations([{ deprecated: "store:application", valid: "service:store" }]); } if (store) { registry.register("service:store", store, { instantiate: false }); } else if (!registry.has("service:store")) { registry.register("service:store", application && application.Store || ember$data$lib$system$store$$default); } } var ember$data$lib$transforms$base$$default = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @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: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: null }); var ember$data$lib$transforms$number$$empty = Ember.isEmpty; function ember$data$lib$transforms$number$$isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } var ember$data$lib$transforms$number$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function (serialized) { var transformed; if (ember$data$lib$transforms$number$$empty(serialized)) { return null; } else { transformed = Number(serialized); return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null; } }, serialize: function (deserialized) { var transformed; if (ember$data$lib$transforms$number$$empty(deserialized)) { return null; } else { transformed = Number(deserialized); return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null; } } }); // Date.prototype.toISOString shim // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString var ember$data$lib$transforms$date$$toISOString = Date.prototype.toISOString || function () { function pad(number) { if (number < 10) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; if (Ember.SHIM_ES5) { if (!Date.prototype.toISOString) { Date.prototype.toISOString = ember$data$lib$transforms$date$$toISOString; } } var ember$data$lib$transforms$date$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function (serialized) { var type = typeof serialized; if (type === 'string') { return new Date(Ember.Date.parse(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) { return ember$data$lib$transforms$date$$toISOString.call(date); } else { return null; } } }); var ember$data$lib$transforms$string$$none = Ember.isNone; var ember$data$lib$transforms$string$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function (serialized) { return ember$data$lib$transforms$string$$none(serialized) ? null : String(serialized); }, serialize: function (deserialized) { return ember$data$lib$transforms$string$$none(deserialized) ? null : String(deserialized); } }); var ember$data$lib$transforms$boolean$$default = ember$data$lib$transforms$base$$default.extend({ deserialize: function (serialized) { var type = typeof serialized; 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) { return Boolean(deserialized); } }); var ember$data$lib$initializers$transforms$$default = ember$data$lib$initializers$transforms$$initializeTransforms; /** Configures a registry for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Registry} registry */ function ember$data$lib$initializers$transforms$$initializeTransforms(registry) { registry.register('transform:boolean', ember$data$lib$transforms$boolean$$default); registry.register('transform:date', ember$data$lib$transforms$date$$default); registry.register('transform:number', ember$data$lib$transforms$number$$default); registry.register('transform:string', ember$data$lib$transforms$string$$default); } var ember$data$lib$initializers$store$injections$$default = ember$data$lib$initializers$store$injections$$initializeStoreInjections; /** 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 ember$data$lib$initializers$store$injections$$initializeStoreInjections(registry) { registry.injection('controller', 'store', 'service:store'); registry.injection('route', 'store', 'service:store'); registry.injection('data-adapter', 'store', 'service:store'); } var ember$data$lib$system$model$attributes$$default = ember$data$lib$system$model$attributes$$attr; /** @module ember-data */ var ember$data$lib$system$model$attributes$$get = Ember.get; /** @class Model @namespace DS */ ember$data$lib$system$model$model$$default.reopenClass({ /** 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: attr('string'), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var attributes = Ember.get(Person, 'attributes') attributes.forEach(function(name, meta) { 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.computed(function () { var map = ember$data$lib$system$map$$Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.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: attr(), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var 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.computed(function () { var map = ember$data$lib$system$map$$Map.create(); this.eachAttribute(function (key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); Person.eachAttribute(function(name, meta) { 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"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachAttribute: function (callback, binding) { ember$data$lib$system$model$attributes$$get(this, "attributes").forEach(function (meta, name) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachTransformedAttribute: function (callback, binding) { ember$data$lib$system$model$attributes$$get(this, "transformedAttributes").forEach(function (type, name) { callback.call(binding, name, type); }); } }); ember$data$lib$system$model$model$$default.reopen({ eachAttribute: function (callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function ember$data$lib$system$model$attributes$$getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { return options.defaultValue; } } function ember$data$lib$system$model$attributes$$hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || key in record._data; } function ember$data$lib$system$model$attributes$$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: attr('string'), email: attr('string'), settings: attr({defaultValue: function() { return {}; }}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function ember$data$lib$system$model$attributes$$attr(type, options) { if (typeof type === "object") { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return ember$new$computed$lib$main$$default({ get: function (key) { var internalModel = this._internalModel; if (ember$data$lib$system$model$attributes$$hasValue(internalModel, key)) { return ember$data$lib$system$model$attributes$$getValue(internalModel, key); } else { return ember$data$lib$system$model$attributes$$getDefaultValue(this, options, key); } }, set: function (key, value) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== "id"); var internalModel = this._internalModel; var oldValue = ember$data$lib$system$model$attributes$$getValue(internalModel, key); 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; this._internalModel.send("didSetProperty", { name: key, oldValue: oldValue, originalValue: internalModel._data[key], value: value }); } return value; } }).meta(meta); } var ember$data$lib$system$model$$default = ember$data$lib$system$model$model$$default; var ember$data$lib$system$debug$debug$adapter$$get = Ember.get; var ember$data$lib$system$debug$debug$adapter$$capitalize = Ember.String.capitalize; var ember$data$lib$system$debug$debug$adapter$$underscore = Ember.String.underscore; var ember$data$lib$system$debug$debug$adapter$$_Ember = Ember; var ember$data$lib$system$debug$debug$adapter$$assert = ember$data$lib$system$debug$debug$adapter$$_Ember.assert; var ember$data$lib$system$debug$debug$adapter$$default = Ember.DataAdapter.extend({ getFilters: function () { return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; }, detect: function (typeClass) { return typeClass !== ember$data$lib$system$model$$default && ember$data$lib$system$model$$default.detect(typeClass); }, columnsForType: function (typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; ember$data$lib$system$debug$debug$adapter$$get(typeClass, 'attributes').forEach(function (meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = ember$data$lib$system$debug$debug$adapter$$capitalize(ember$data$lib$system$debug$debug$adapter$$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]; } } } ember$data$lib$system$debug$debug$adapter$$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 self = this; var count = 0; var columnValues = { id: ember$data$lib$system$debug$debug$adapter$$get(record, 'id') }; record.eachAttribute(function (key) { if (count++ > self.attributeLimit) { return false; } var value = ember$data$lib$system$debug$debug$adapter$$get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function (record) { var keywords = []; var keys = Ember.A(['id']); record.eachAttribute(function (key) { keys.push(key); }); keys.forEach(function (key) { keywords.push(ember$data$lib$system$debug$debug$adapter$$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.A(); var self = this; var keysToObserve = Ember.A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute(function (key) { keysToObserve.push(key); }); keysToObserve.forEach(function (key) { var handler = function () { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function () { Ember.removeObserver(record, key, handler); }); }); var release = function () { releaseMethods.forEach(function (fn) { fn(); }); }; return release; } }); var ember$data$lib$initializers$data$adapter$$default = ember$data$lib$initializers$data$adapter$$initializeDebugAdapter; /** 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 ember$data$lib$initializers$data$adapter$$initializeDebugAdapter(registry) { registry.register("data-adapter:main", ember$data$lib$system$debug$debug$adapter$$default); } var ember$data$lib$instance$initializers$initialize$store$service$$default = ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService; /** Configures a registry for use with an Ember-Data store. @method initializeStore @param {Ember.ApplicationInstance} applicationOrRegistry */ function ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService(applicationOrRegistry) { var registry, container; if (applicationOrRegistry.registry && applicationOrRegistry.container) { // initializeStoreService was registered with an // instanceInitializer. The first argument is the application // instance. registry = applicationOrRegistry.registry; container = applicationOrRegistry.container; } else { // initializeStoreService was called by an initializer instead of // an instanceInitializer. The first argument is a registy. This // case allows ED to support Ember pre 1.12 registry = applicationOrRegistry; if (registry.container) { // Support Ember 1.10 - 1.11 container = registry.container(); } else { // Support Ember 1.9 container = registry; } } // Eagerly generate the store so defaultStore is populated. container.lookup('service:store'); } var ember$data$lib$setup$container$$default = ember$data$lib$setup$container$$setupContainer; function ember$data$lib$setup$container$$setupContainer(registry, application) { // application is not a required argument. This ensures // testing setups can setup a container without booting an // entire ember application. ember$data$lib$setup$container$$initializeInjects(registry, application); ember$data$lib$instance$initializers$initialize$store$service$$default(registry); } function ember$data$lib$setup$container$$initializeInjects(registry, application) { ember$data$lib$initializers$data$adapter$$default(registry, application); ember$data$lib$initializers$transforms$$default(registry, application); ember$data$lib$initializers$store$injections$$default(registry, application); activemodel$adapter$lib$setup$container$$default(registry, application); ember$data$lib$initializers$store$$default(registry, application); } var ember$data$lib$ember$initializer$$K = Ember.K; /** @module ember-data */ /* This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.StoreService` (or via a module system that resolves to `service:store`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.StoreService = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function (Application) { Application.initializer({ name: 'ember-data', initialize: ember$data$lib$setup$container$$initializeInjects }); if (Application.instanceInitializer) { Application.instanceInitializer({ name: 'ember-data', initialize: ember$data$lib$instance$initializers$initialize$store$service$$default }); } else { Application.initializer({ name: 'ember-data-store-service', after: 'ember-data', initialize: ember$data$lib$instance$initializers$initialize$store$service$$default }); } // Deprecated initializers to satisfy old code that depended on them Application.initializer({ name: 'store', after: 'ember-data', initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: 'activeModelAdapter', before: 'store', initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: 'transforms', before: 'store', initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: 'data-adapter', before: 'store', initialize: ember$data$lib$ember$initializer$$K }); Application.initializer({ name: 'injectStore', before: 'store', initialize: ember$data$lib$ember$initializer$$K }); }); Ember.Date = Ember.Date || {}; var origParse = Date.parse; var numericKeys = [1, 4, 5, 6, 7, 10, 11]; /** @method parse @param {Date} date @return {Number} timestamp */ Ember.Date.parse = function (date) { var timestamp, struct; var minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date)) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; k = numericKeys[i]; ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } ember$data$lib$system$model$$default.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function () { var attributes = ['id']; var relationships = { belongsTo: [], hasMany: [] }; var expensiveProperties = []; this.eachAttribute(function (name, meta) { attributes.push(name); }, this); this.eachRelationship(function (name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [{ name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { 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 } }; } }); var ember$data$lib$system$debug$debug$info$$default = ember$data$lib$system$model$$default; var ember$data$lib$system$debug$$default = ember$data$lib$system$debug$debug$adapter$$default; var ember$data$lib$serializers$embedded$records$mixin$$get = Ember.get; var ember$data$lib$serializers$embedded$records$mixin$$set = Ember.set; var ember$data$lib$serializers$embedded$records$mixin$$forEach = Ember.ArrayPolyfills.forEach; var ember$data$lib$serializers$embedded$records$mixin$$camelize = Ember.String.camelize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer then define and configure embedded (model) relationships. Below is an example of a per-type serializer ('post' type). ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the ActiveModelSerializer. Nevertheless, using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup embedded records. The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: ```js { serialize: 'records', deserialize: 'records' } ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the ApplicationSerializer or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async:true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded for deserialization. If a model is declared embedded for deserialization (`embedded: 'always'`, `deserialize: 'record'` or `deserialize: 'records'`), then do not use `async:true`. To successfully extract and serialize embedded records the model relationships must be setup correcty See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ var ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin = Ember.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); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind, 'serialize'); if (!embeddedSnapshot) { json[key] = null; } else { json[key] = embeddedSnapshot.id; } } else if (includeRecords) { key = this.keyForAttribute(attr, 'serialize'); if (!embeddedSnapshot) { json[key] = null; } else { json[key] = embeddedSnapshot.record.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key]); } } }, /** Serialize `hasMany` relationship 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` 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"] } } ``` @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; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var key, hasMany; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind, 'serialize'); json[key] = snapshot.hasMany(attr, { ids: true }); } else if (includeRecords) { key = this.keyForAttribute(attr, 'serialize'); hasMany = snapshot.hasMany(attr); Ember.warn('The embedded relationship \'' + key + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', Ember.typeOf(hasMany) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' }); json[key] = Ember.A(hasMany).map(function (embeddedSnapshot) { var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); return embeddedJson; }, this); } }, /** 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 === 'hasMany') { return; } else 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); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + embeddedSerializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'isNewSerializerAPI')); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); if (parentKey) { delete json[parentKey]; } } } }, // 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 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[ember$data$lib$serializers$embedded$records$mixin$$camelize(attr)] || attrs[attr]); }, /** @method _extractEmbeddedRecords @private */ _extractEmbeddedRecords: function (serializer, store, typeClass, partial) { if (this.get('isNewSerializerAPI')) { return ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedRecords.apply(this, arguments); } typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { var embeddedTypeClass = store.modelFor(relationship.type); if (relationship.kind === 'hasMany') { if (relationship.options.polymorphic) { this._extractEmbeddedHasManyPolymorphic(store, key, partial); } else { this._extractEmbeddedHasMany(store, key, embeddedTypeClass, partial); } } if (relationship.kind === 'belongsTo') { if (relationship.options.polymorphic) { this._extractEmbeddedBelongsToPolymorphic(store, key, partial); } else { this._extractEmbeddedBelongsTo(store, key, embeddedTypeClass, partial); } } } }, this); return partial; }, /** @method _extractEmbeddedHasMany @private */ _extractEmbeddedHasMany: function (store, key, embeddedTypeClass, hash) { if (this.get('isNewSerializerAPI')) { return ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedHasMany.apply(this, arguments); } if (!hash[key]) { return hash; } var ids = []; var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + embeddedSerializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'isNewSerializerAPI')); ember$data$lib$serializers$embedded$records$mixin$$forEach.call(hash[key], function (data) { var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass.modelName, embeddedRecord); ids.push(embeddedRecord.id); }); hash[key] = ids; return hash; }, /** @method _extractEmbeddedHasManyPolymorphic @private */ _extractEmbeddedHasManyPolymorphic: function (store, key, hash) { var _this = this; if (!hash[key]) { return hash; } var ids = []; ember$data$lib$serializers$embedded$records$mixin$$forEach.call(hash[key], function (data) { var modelName = data.type; var embeddedSerializer = store.serializerFor(modelName); Ember.assert(_this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(_this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + embeddedSerializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(_this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'isNewSerializerAPI')); var embeddedTypeClass = store.modelFor(modelName); // var primaryKey = embeddedSerializer.get('primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass.modelName, embeddedRecord); ids.push({ id: embeddedRecord.id, type: modelName }); }); hash[key] = ids; return hash; }, /** @method _extractEmbeddedBelongsTo @private */ _extractEmbeddedBelongsTo: function (store, key, embeddedTypeClass, hash) { if (this.get('isNewSerializerAPI')) { return ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedBelongsTo.apply(this, arguments); } if (!hash[key]) { return hash; } var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + embeddedSerializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'isNewSerializerAPI')); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, hash[key], null); store.push(embeddedTypeClass.modelName, embeddedRecord); hash[key] = embeddedRecord.id; return hash; }, /** @method _extractEmbeddedBelongsToPolymorphic @private */ _extractEmbeddedBelongsToPolymorphic: function (store, key, hash) { if (!hash[key]) { return hash; } var data = hash[key]; var modelName = data.type; var embeddedSerializer = store.serializerFor(modelName); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + embeddedSerializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'isNewSerializerAPI')); var embeddedTypeClass = store.modelFor(modelName); // var primaryKey = embeddedSerializer.get('primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass.modelName, embeddedRecord); hash[key] = embeddedRecord.id; hash[key + 'Type'] = modelName; return hash; }, /** @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); Ember.assert(this.toString() + ' is using the ' + (ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') ? 'new' : 'old') + ' serializer API and expects ' + serializer.toString() + ' it collaborates with to do the same. Make sure to set `isNewSerializerAPI: true` in your custom serializers if you want to use the new Serializer API.', ember$data$lib$serializers$embedded$records$mixin$$get(this, 'isNewSerializerAPI') === ember$data$lib$serializers$embedded$records$mixin$$get(serializer, 'isNewSerializerAPI')); return serializer.normalize(modelClass, relationshipHash, null); } }); var ember$data$lib$serializers$embedded$records$mixin$$default = ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin; /* @method _newExtractEmbeddedRecords @private */ function ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedRecords(serializer, store, typeClass, partial) { var _this2 = this; typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { if (relationship.kind === 'hasMany') { _this2._extractEmbeddedHasMany(store, key, partial, relationship); } if (relationship.kind === 'belongsTo') { _this2._extractEmbeddedBelongsTo(store, key, partial, relationship); } } }, this); return partial; } /* @method _newExtractEmbeddedHasMany @private */ function ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedHasMany(store, key, hash, relationshipMeta) { var _this3 = this; var relationshipHash = ember$data$lib$serializers$embedded$records$mixin$$get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var hasMany = relationshipHash.map(function (item) { var _normalizeEmbeddedRelationship = _this3._normalizeEmbeddedRelationship(store, relationshipMeta, item); var data = _normalizeEmbeddedRelationship.data; var included = _normalizeEmbeddedRelationship.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included; (_hash$included = hash.included).push.apply(_hash$included, included); } return { id: data.id, type: data.type }; }); var relationship = { data: hasMany }; ember$data$lib$serializers$embedded$records$mixin$$set(hash, 'data.relationships.' + key, relationship); } /* @method _newExtractEmbeddedBelongsTo @private */ function ember$data$lib$serializers$embedded$records$mixin$$_newExtractEmbeddedBelongsTo(store, key, hash, relationshipMeta) { var relationshipHash = ember$data$lib$serializers$embedded$records$mixin$$get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var _normalizeEmbeddedRelationship2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash); var data = _normalizeEmbeddedRelationship2.data; var included = _normalizeEmbeddedRelationship2.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included2; (_hash$included2 = hash.included).push.apply(_hash$included2, included); } var belongsTo = { id: data.id, type: data.type }; var relationship = { data: belongsTo }; ember$data$lib$serializers$embedded$records$mixin$$set(hash, 'data.relationships.' + key, relationship); } /** `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 ember$data$lib$system$relationships$belongs$to$$belongsTo(modelName, options) { var opts, userEnteredModelName; if (typeof modelName === "object") { opts = modelName; userEnteredModelName = undefined; } else { opts = options; userEnteredModelName = modelName; } if (typeof userEnteredModelName === "string") { userEnteredModelName = ember$data$lib$system$normalize$model$name$$default(userEnteredModelName); } Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + Ember.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 shouldWarnAsync = false; if (typeof opts.async === "undefined") { shouldWarnAsync = true; } var meta = { type: userEnteredModelName, isRelationship: true, options: opts, kind: "belongsTo", key: null, shouldWarnAsync: shouldWarnAsync }; return ember$new$computed$lib$main$$default({ get: function (key) { if (opts.hasOwnProperty("serialize")) { Ember.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 http://emberjs.com/api/data/classes/DS.Serializer.html", false, { id: "ds.model.serialize-option-in-belongs-to" }); } if (opts.hasOwnProperty("embedded")) { Ember.warn("You provided an embedded option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html", false, { id: "ds.model.embedded-option-in-belongs-to" }); } if (meta.shouldWarnAsync) { Ember.deprecate("In Ember Data 2.0, relationships will be asynchronous by default. You must set `" + key + ": DS.belongsTo('" + modelName + "', { async: false })` if you wish for a relationship remain synchronous.", false, { id: "ds.model.relationship-changing-to-asynchrounous-by-default", until: "2.0.0" }); meta.shouldWarnAsycn = false; } 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).setRecord(value._internalModel); } else { this._internalModel._relationships.get(key).setRecord(value); } return this._internalModel._relationships.get(key).getRecord(); } }).meta(meta); } /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ ember$data$lib$system$model$$default.reopen({ notifyBelongsToChanged: function (key) { this.notifyPropertyChange(key); } }); var ember$data$lib$system$relationships$belongs$to$$default = ember$data$lib$system$relationships$belongs$to$$belongsTo; /** `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`/`hasManys` 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 ember$data$lib$system$relationships$has$many$$hasMany(type, options) { if (typeof type === "object") { options = type; type = undefined; } Ember.assert("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + Ember.inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === "string" || typeof type === "undefined"); options = options || {}; var shouldWarnAsync = false; if (typeof options.async === "undefined") { shouldWarnAsync = true; } if (typeof type === "string") { type = ember$data$lib$system$normalize$model$name$$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, isRelationship: true, options: options, kind: "hasMany", key: null, shouldWarnAsync: shouldWarnAsync }; return ember$new$computed$lib$main$$default({ get: function (key) { if (meta.shouldWarnAsync) { Ember.deprecate("In Ember Data 2.0, relationships will be asynchronous by default. You must set `" + key + ": DS.hasMany('" + type + "', { async: false })` if you wish for a relationship remain synchronous.", false, { id: "ds.model.relationship-changing-to-asynchrounous-by-default", until: "2.0.0" }); meta.shouldWarnAsync = false; } var relationship = this._internalModel._relationships.get(key); return relationship.getRecords(); }, set: function (key, records) { var relationship = this._internalModel._relationships.get(key); relationship.clear(); Ember.assert("You must pass an array of records to set a hasMany relationship", Ember.isArray(records)); relationship.addRecords(Ember.A(records).mapBy("_internalModel")); return relationship.getRecords(); } }).meta(meta); } ember$data$lib$system$model$$default.reopen({ 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); } }); var ember$data$lib$system$relationships$has$many$$default = ember$data$lib$system$relationships$has$many$$hasMany; function ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta) { var modelName; modelName = meta.type || meta.key; if (meta.kind === 'hasMany') { modelName = ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(modelName)); } return modelName; } function ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta) { return { key: meta.key, kind: meta.kind, type: ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } var ember$data$lib$system$relationships$ext$$get = Ember.get; var ember$data$lib$system$relationships$ext$$filter = Ember.ArrayPolyfills.filter; var ember$data$lib$system$relationships$ext$$relationshipsDescriptor = Ember.computed(function () { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable = false; } var map = new ember$data$lib$system$map$$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(ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var ember$data$lib$system$relationships$ext$$relatedTypesDescriptor = Ember.computed(function () { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable = false; } var modelName; var types = Ember.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 = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta); Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", modelName); if (!types.contains(modelName)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!modelName); types.push(modelName); } } }); return types; }).readOnly(); var ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor = Ember.computed(function () { if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable === true) { ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable = false; } var map = ember$data$lib$system$map$$Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta); relationship.type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta); map.set(name, relationship); } }); return map; }).readOnly(); /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ ember$data$lib$system$model$$default.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function (proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.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; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ ember$data$lib$system$model$$default.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @param {store} store an instance of DS.Store @return {DS.Model} the type of the relationship, or undefined */ typeForRelationship: function (name, store) { var relationship = ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").get(name); return relationship && store.modelFor(relationship.type); }, inverseMap: Ember.computed(function () { return ember$data$lib$system$object$polyfills$$create(null); }), /** Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('message') }); ``` ```app/models/message.js import DS from 'ember-data'; export default DS.Model.extend({ owner: DS.belongsTo('post') }); ``` App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' } App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' } @method inverseFor @static @param {String} name the name of the relationship @return {Object} the inverse relationship, or null */ inverseFor: function (name, store) { var inverseMap = ember$data$lib$system$relationships$ext$$get(this, "inverseMap"); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name, store); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _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, inverseKind, inverse; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = Ember.get(inverseType, "relationshipsByName").get(inverseName); Ember.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.isNone(inverse)); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one if (propertyMeta.type === propertyMeta.parentType.modelName) { Ember.warn("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://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); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = ember$data$lib$system$relationships$ext$$filter.call(possibleRelationships, function (possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); Ember.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); if (filteredRelationships.length === 1) { possibleRelationships = filteredRelationships; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://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; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = ember$data$lib$system$relationships$ext$$get(inverseType, "relationships"); if (!relationshipMap) { return possibleRelationships; } var relationships = relationshipMap.get(type.modelName); relationships = ember$data$lib$system$relationships$ext$$filter.call(relationships, 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, possibleRelationships); } return possibleRelationships; } 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'; var relationships = Ember.get(Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: ember$data$lib$system$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'; var relationshipNames = Ember.get(Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.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'; var relatedTypes = Ember.get(Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: ember$data$lib$system$relationships$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'; var relationshipsByName = Ember.get(Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: ember$data$lib$system$relationships$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'; var 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.computed(function () { var map = ember$data$lib$system$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(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").forEach(function (relationship, name) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function (callback, binding) { ember$data$lib$system$relationships$ext$$get(this, "relatedTypes").forEach(function (type) { callback.call(binding, type); }); }, determineRelationshipType: function (knownSide, store) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey, store); var key, otherKind; 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"; } } }); ember$data$lib$system$model$$default.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, descriptor); ``` - `name` the name of the current property in the iteration - `descriptor` the meta object that describes this relationship The relationship descriptor argument is an object with the following properties. - **key** <span class="type">String</span> the name of this relationship on the Model - **kind** <span class="type">String</span> "hasMany" or "belongsTo" - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared - **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship - **type** <span class="type">DS.Model</span> the type of the related Model Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachRelationship(function(name, descriptor) { if (descriptor.kind === 'hasMany') { var serializedHasManyName = name.toUpperCase() + '_IDS'; json[name.toUpperCase()] = record.get(name).mapBy('id'); } }); return json; } }); ``` @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function (name) { return ember$data$lib$system$relationships$ext$$get(this.constructor, "relationshipsByName").get(name); }, inverseFor: function (key) { return this.constructor.inverseFor(key, this.store); } }); /** Ember Data @module ember-data @main ember-data */ if (Ember.VERSION.match(/^1\.[0-7]\./)) { throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have " + Ember.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data"); } if (Ember.VERSION.match(/^1\.12\.0/)) { throw new Ember.Error("Ember Data does not work with Ember 1.12.0. Please upgrade to Ember 1.12.1 or higher."); } // support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;ember$data$lib$core$$default.Store = ember$data$lib$system$store$$Store; ember$data$lib$core$$default.PromiseArray = ember$data$lib$system$promise$proxies$$PromiseArray; ember$data$lib$core$$default.PromiseObject = ember$data$lib$system$promise$proxies$$PromiseObject; ember$data$lib$core$$default.PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseManyArray; ember$data$lib$core$$default.Model = ember$data$lib$system$model$$default; ember$data$lib$core$$default.RootState = ember$data$lib$system$model$states$$default; ember$data$lib$core$$default.attr = ember$data$lib$system$model$attributes$$default; ember$data$lib$core$$default.Errors = ember$data$lib$system$model$errors$$default; ember$data$lib$core$$default.InternalModel = ember$data$lib$system$model$internal$model$$default; ember$data$lib$core$$default.Snapshot = ember$data$lib$system$snapshot$$default; ember$data$lib$core$$default.Adapter = ember$data$lib$system$adapter$$default; ember$data$lib$core$$default.AdapterError = ember$data$lib$adapters$errors$$AdapterError; ember$data$lib$core$$default.InvalidError = ember$data$lib$adapters$errors$$InvalidError; ember$data$lib$core$$default.TimeoutError = ember$data$lib$adapters$errors$$TimeoutError; ember$data$lib$core$$default.AbortError = ember$data$lib$adapters$errors$$AbortError; ember$data$lib$core$$default.errorsHashToArray = ember$data$lib$adapters$errors$$errorsHashToArray; ember$data$lib$core$$default.errorsArrayToHash = ember$data$lib$adapters$errors$$errorsArrayToHash; ember$data$lib$core$$default.Serializer = ember$data$lib$system$serializer$$default; ember$data$lib$core$$default.DebugAdapter = ember$data$lib$system$debug$$default; ember$data$lib$core$$default.RecordArray = ember$data$lib$system$record$arrays$record$array$$default; ember$data$lib$core$$default.FilteredRecordArray = ember$data$lib$system$record$arrays$filtered$record$array$$default; ember$data$lib$core$$default.AdapterPopulatedRecordArray = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default; ember$data$lib$core$$default.ManyArray = ember$data$lib$system$many$array$$default; ember$data$lib$core$$default.RecordArrayManager = ember$data$lib$system$record$array$manager$$default; ember$data$lib$core$$default.RESTAdapter = ember$data$lib$adapters$rest$adapter$$default; ember$data$lib$core$$default.BuildURLMixin = ember$data$lib$adapters$build$url$mixin$$default; ember$data$lib$core$$default.RESTSerializer = ember$data$lib$serializers$rest$serializer$$default; ember$data$lib$core$$default.JSONSerializer = ember$data$lib$serializers$json$serializer$$default; ember$data$lib$core$$default.JSONAPIAdapter = ember$data$lib$adapters$json$api$adapter$$default; ember$data$lib$core$$default.JSONAPISerializer = ember$data$lib$serializers$json$api$serializer$$default; ember$data$lib$core$$default.Transform = ember$data$lib$transforms$base$$default; ember$data$lib$core$$default.DateTransform = ember$data$lib$transforms$date$$default; ember$data$lib$core$$default.StringTransform = ember$data$lib$transforms$string$$default; ember$data$lib$core$$default.NumberTransform = ember$data$lib$transforms$number$$default; ember$data$lib$core$$default.BooleanTransform = ember$data$lib$transforms$boolean$$default; var ember$data$lib$main$$_ActiveModelAdapter = activemodel$adapter$lib$system$active$model$adapter$$default; var ember$data$lib$main$$_ActiveModelSerializer = activemodel$adapter$lib$system$active$model$serializer$$default; if (Ember.platform.hasPropertyAccessors) { Ember.defineProperty(ember$data$lib$core$$default, "ActiveModelAdapter", { get: function () { if (ember$data$lib$main$$_ActiveModelSerializer === activemodel$adapter$lib$system$active$model$adapter$$default) { Ember.deprecate("The ActiveModelAdapter has been moved into a plugin. It will not be bundled with Ember Data in 2.0", false, { url: "https://github.com/ember-data/active-model-adapter", id: "ds.adapter.active-model-adapter-deprecated", until: "2.0.0" }); } return ember$data$lib$main$$_ActiveModelAdapter; }, set: function (ActiveModelAdapter) { ember$data$lib$main$$_ActiveModelAdapter = ActiveModelAdapter; } }); Ember.defineProperty(ember$data$lib$core$$default, "ActiveModelSerializer", { get: function () { if (ember$data$lib$main$$_ActiveModelSerializer === activemodel$adapter$lib$system$active$model$serializer$$default) { Ember.deprecate("The ActiveModelSerializer has been moved into a plugin. It will not be bundled with Ember Data in 2.0", false, { url: "https://github.com/ember-data/active-model-adapter", id: "ds.serializer.active-model-serializer-deprecated", until: "2.0.0" }); } return ember$data$lib$main$$_ActiveModelSerializer; }, set: function (ActiveModelSerializer) { ember$data$lib$main$$_ActiveModelSerializer = ActiveModelSerializer; } }); } else { ember$data$lib$core$$default.ActiveModelAdapter = activemodel$adapter$lib$system$active$model$adapter$$default; ember$data$lib$core$$default.ActiveModelSerializer = activemodel$adapter$lib$system$active$model$serializer$$default; } ember$data$lib$core$$default.EmbeddedRecordsMixin = ember$data$lib$serializers$embedded$records$mixin$$default; ember$data$lib$core$$default.belongsTo = ember$data$lib$system$relationships$belongs$to$$default; ember$data$lib$core$$default.hasMany = ember$data$lib$system$relationships$has$many$$default; ember$data$lib$core$$default.Relationship = ember$data$lib$system$relationships$state$relationship$$default; ember$data$lib$core$$default.ContainerProxy = ember$data$lib$system$container$proxy$$default; ember$data$lib$core$$default._setupContainer = ember$data$lib$setup$container$$default; Ember.defineProperty(ember$data$lib$core$$default, "normalizeModelName", { enumerable: true, writable: false, configurable: false, value: ember$data$lib$system$normalize$model$name$$default }); var ember$data$lib$main$$_FixtureAdapter = ember$data$lib$adapters$fixture$adapter$$default; if (Ember.platform.hasPropertyAccessors) { Ember.defineProperty(ember$data$lib$core$$default, "FixtureAdapter", { get: function () { if (ember$data$lib$main$$_FixtureAdapter === ember$data$lib$adapters$fixture$adapter$$default) { Ember.deprecate("DS.FixtureAdapter has been deprecated and moved into an unsupported addon: https://github.com/emberjs/ember-data-fixture-adapter/tree/master", false, { id: "ds.adapter.fixture-adapter-deprecated", until: "2.0.0" }); } return ember$data$lib$main$$_FixtureAdapter; }, set: function (FixtureAdapter) { ember$data$lib$main$$_FixtureAdapter = FixtureAdapter; } }); } else { ember$data$lib$core$$default.FixtureAdapter = ember$data$lib$adapters$fixture$adapter$$default; } Ember.lookup.DS = ember$data$lib$core$$default; var ember$data$lib$main$$default = ember$data$lib$core$$default; }).call(this); //# sourceMappingURL=ember-data.js.map
src/components/app.js
januswel/rn-pomodoro
// @flow import React from 'react' import { StyleSheet, Text, View, } from 'react-native' const COLORS = { VERY_PALE_BLUE: '#f5fcff', } const STYLES = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: COLORS.VERY_PALE_BLUE, }, text: { fontSize: 20, textAlign: 'center', margin: 10, }, }) export default function App() { return ( <View style={STYLES.container}> <Text style={STYLES.text}>app</Text> </View> ) }
src/index.js
dizzyrobin/um-schedule-creator
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
ajax/libs/yasr/2.4.0/yasr.bundled.min.js
dmsanchez86/cdnjs
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.YASR=t()}}(function(){var t;return function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(t,e){e.exports=t("./main.js")},{"./main.js":35}],2:[function(e,n,r){(function(n,i,o){(function(n){"use strict";"function"==typeof t&&t.amd?t("datatables",["jquery"],n):"object"==typeof r?n(e("jquery")):jQuery&&!jQuery.fn.dataTable&&n(jQuery)})(function(t){"use strict";function e(n){var r,i,o="a aa ai ao as b fn i m o s ",a={};t.each(n,function(t){r=t.match(/^([^A-Z]+?)([A-Z])/);if(r&&-1!==o.indexOf(r[1]+" ")){i=t.replace(r[0],r[2].toLowerCase());a[i]=t;"o"===r[1]&&e(n[t])}});n._hungarianMap=a}function r(n,i,a){n._hungarianMap||e(n);var s;t.each(i,function(e){s=n._hungarianMap[e];if(s!==o&&(a||i[s]===o))if("o"===s.charAt(0)){i[s]||(i[s]={});t.extend(!0,i[s],i[e]);r(n[s],i[s],a)}else i[s]=i[e]})}function a(t){var e=$e.defaults.oLanguage,n=t.sZeroRecords;!t.sEmptyTable&&n&&"No data available in table"===e.sEmptyTable&&Oe(t,t,"sZeroRecords","sEmptyTable");!t.sLoadingRecords&&n&&"Loading..."===e.sLoadingRecords&&Oe(t,t,"sZeroRecords","sLoadingRecords");t.sInfoThousands&&(t.sThousands=t.sInfoThousands);var r=t.sDecimal;r&&Xe(r)}function s(t){yn(t,"ordering","bSort");yn(t,"orderMulti","bSortMulti");yn(t,"orderClasses","bSortClasses");yn(t,"orderCellsTop","bSortCellsTop");yn(t,"order","aaSorting");yn(t,"orderFixed","aaSortingFixed");yn(t,"paging","bPaginate");yn(t,"pagingType","sPaginationType");yn(t,"pageLength","iDisplayLength");yn(t,"searching","bFilter");var e=t.aoSearchCols;if(e)for(var n=0,i=e.length;i>n;n++)e[n]&&r($e.models.oSearch,e[n])}function l(t){yn(t,"orderable","bSortable");yn(t,"orderData","aDataSort");yn(t,"orderSequence","asSorting");yn(t,"orderDataType","sortDataType")}function u(e){var n=e.oBrowser,r=t("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(t("<div/>").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(t('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),i=r.find(".test");n.bScrollOversize=100===i[0].offsetWidth;n.bScrollbarLeft=1!==i.offset().left;r.remove()}function c(t,e,n,r,i,a){var s,l=r,u=!1;if(n!==o){s=n;u=!0}for(;l!==i;)if(t.hasOwnProperty(l)){s=u?e(s,t[l],l,t):t[l];u=!0;l+=a}return s}function f(e,n){var r=$e.defaults.column,o=e.aoColumns.length,a=t.extend({},$e.models.oColumn,r,{nTh:n?n:i.createElement("th"),sTitle:r.sTitle?r.sTitle:n?n.innerHTML:"",aDataSort:r.aDataSort?r.aDataSort:[o],mData:r.mData?r.mData:o,idx:o});e.aoColumns.push(a);var s=e.aoPreSearchCols;s[o]=t.extend({},$e.models.oSearch,s[o]);h(e,o,null)}function h(e,n,i){var a=e.aoColumns[n],s=e.oClasses,u=t(a.nTh);if(!a.sWidthOrig){a.sWidthOrig=u.attr("width")||null;var c=(u.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);c&&(a.sWidthOrig=c[1])}if(i!==o&&null!==i){l(i);r($e.defaults.column,i);i.mDataProp===o||i.mData||(i.mData=i.mDataProp);i.sType&&(a._sManualType=i.sType);i.className&&!i.sClass&&(i.sClass=i.className);t.extend(a,i);Oe(a,i,"sWidth","sWidthOrig");"number"==typeof i.iDataSort&&(a.aDataSort=[i.iDataSort]);Oe(a,i,"aDataSort")}var f=a.mData,h=M(f),d=a.mRender?M(a.mRender):null,p=function(t){return"string"==typeof t&&-1!==t.indexOf("@")};a._bAttrSrc=t.isPlainObject(f)&&(p(f.sort)||p(f.type)||p(f.filter));a.fnGetData=function(t,e,n){var r=h(t,e,o,n);return d&&e?d(r,e,t,n):r};a.fnSetData=function(t,e,n){return D(f)(t,e,n)};if(!e.oFeatures.bSort){a.bSortable=!1;u.addClass(s.sSortableNone)}var g=-1!==t.inArray("asc",a.asSorting),m=-1!==t.inArray("desc",a.asSorting);if(a.bSortable&&(g||m))if(g&&!m){a.sSortingClass=s.sSortableAsc;a.sSortingClassJUI=s.sSortJUIAscAllowed}else if(!g&&m){a.sSortingClass=s.sSortableDesc;a.sSortingClassJUI=s.sSortJUIDescAllowed}else{a.sSortingClass=s.sSortable;a.sSortingClassJUI=s.sSortJUI}else{a.sSortingClass=s.sSortableNone;a.sSortingClassJUI=""}}function d(t){if(t.oFeatures.bAutoWidth!==!1){var e=t.aoColumns;ye(t);for(var n=0,r=e.length;r>n;n++)e[n].nTh.style.width=e[n].sWidth}var i=t.oScroll;(""!==i.sY||""!==i.sX)&&me(t);ze(t,null,"column-sizing",[t])}function p(t,e){var n=v(t,"bVisible");return"number"==typeof n[e]?n[e]:null}function g(e,n){var r=v(e,"bVisible"),i=t.inArray(n,r);return-1!==i?i:null}function m(t){return v(t,"bVisible").length}function v(e,n){var r=[];t.map(e.aoColumns,function(t,e){t[n]&&r.push(e)});return r}function y(t){var e,n,r,i,a,s,l,u,c,f=t.aoColumns,h=t.aoData,d=$e.ext.type.detect;for(e=0,n=f.length;n>e;e++){l=f[e];c=[];if(!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){for(r=0,i=d.length;i>r;r++){for(a=0,s=h.length;s>a;a++){c[a]===o&&(c[a]=T(t,a,e,"type"));u=d[r](c[a],t);if(!u||"html"===u)break}if(u){l.sType=u;break}}l.sType||(l.sType="string")}}}function b(e,n,r,i){var a,s,l,u,c,h,d,p=e.aoColumns;if(n)for(a=n.length-1;a>=0;a--){d=n[a];var g=d.targets!==o?d.targets:d.aTargets;t.isArray(g)||(g=[g]);for(l=0,u=g.length;u>l;l++)if("number"==typeof g[l]&&g[l]>=0){for(;p.length<=g[l];)f(e);i(g[l],d)}else if("number"==typeof g[l]&&g[l]<0)i(p.length+g[l],d);else if("string"==typeof g[l])for(c=0,h=p.length;h>c;c++)("_all"==g[l]||t(p[c].nTh).hasClass(g[l]))&&i(c,d)}if(r)for(a=0,s=r.length;s>a;a++)i(a,r[a])}function x(e,n,r,i){var o=e.aoData.length,a=t.extend(!0,{},$e.models.oRow,{src:r?"dom":"data"});a._aData=n;e.aoData.push(a);for(var s=e.aoColumns,l=0,u=s.length;u>l;l++){r&&k(e,o,l,T(e,o,l));s[l].sType=null}e.aiDisplayMaster.push(o);(r||!e.oFeatures.bDeferRender)&&I(e,o,r,i);return o}function w(e,n){var r;n instanceof t||(n=t(n));return n.map(function(t,n){r=j(e,n);return x(e,r.data,n,r.cells)})}function C(t,e){return e._DT_RowIndex!==o?e._DT_RowIndex:null}function S(e,n,r){return t.inArray(r,e.aoData[n].anCells)}function T(t,e,n,r){var i=t.iDraw,a=t.aoColumns[n],s=t.aoData[e]._aData,l=a.sDefaultContent,u=a.fnGetData(s,r,{settings:t,row:e,col:n});if(u===o){if(t.iDrawError!=i&&null===l){He(t,0,"Requested unknown parameter "+("function"==typeof a.mData?"{function}":"'"+a.mData+"'")+" for row "+e,4);t.iDrawError=i}return l}if(u!==s&&null!==u||null===l){if("function"==typeof u)return u.call(s)}else u=l;return null===u&&"display"==r?"":u}function k(t,e,n,r){var i=t.aoColumns[n],o=t.aoData[e]._aData;i.fnSetData(o,r,{settings:t,row:e,col:n})}function _(e){return t.map(e.match(/(\\.|[^\.])+/g),function(t){return t.replace(/\\./g,".")})}function M(e){if(t.isPlainObject(e)){var n={};t.each(e,function(t,e){e&&(n[t]=M(e))});return function(t,e,r,i){var a=n[e]||n._;return a!==o?a(t,e,r,i):t}}if(null===e)return function(t){return t};if("function"==typeof e)return function(t,n,r,i){return e(t,n,r,i)};if("string"!=typeof e||-1===e.indexOf(".")&&-1===e.indexOf("[")&&-1===e.indexOf("("))return function(t){return t[e]};var r=function(t,e,n){var i,a,s,l;if(""!==n)for(var u=_(n),c=0,f=u.length;f>c;c++){i=u[c].match(bn);a=u[c].match(xn);if(i){u[c]=u[c].replace(bn,"");""!==u[c]&&(t=t[u[c]]);s=[];u.splice(0,c+1);l=u.join(".");for(var h=0,d=t.length;d>h;h++)s.push(r(t[h],e,l));var p=i[0].substring(1,i[0].length-1);t=""===p?s:s.join(p);break}if(a){u[c]=u[c].replace(xn,"");t=t[u[c]]()}else{if(null===t||t[u[c]]===o)return o;t=t[u[c]]}}return t};return function(t,n){return r(t,n,e)}}function D(e){if(t.isPlainObject(e))return D(e._);if(null===e)return function(){};if("function"==typeof e)return function(t,n,r){e(t,"set",n,r)};if("string"!=typeof e||-1===e.indexOf(".")&&-1===e.indexOf("[")&&-1===e.indexOf("("))return function(t,n){t[e]=n};var n=function(t,e,r){for(var i,a,s,l,u,c=_(r),f=c[c.length-1],h=0,d=c.length-1;d>h;h++){a=c[h].match(bn);s=c[h].match(xn);if(a){c[h]=c[h].replace(bn,"");t[c[h]]=[];i=c.slice();i.splice(0,h+1);u=i.join(".");for(var p=0,g=e.length;g>p;p++){l={};n(l,e[p],u);t[c[h]].push(l)}return}if(s){c[h]=c[h].replace(xn,"");t=t[c[h]](e)}(null===t[c[h]]||t[c[h]]===o)&&(t[c[h]]={});t=t[c[h]]}f.match(xn)?t=t[f.replace(xn,"")](e):t[f.replace(bn,"")]=e};return function(t,r){return n(t,r,e)}}function L(t){return dn(t.aoData,"_aData")}function A(t){t.aoData.length=0;t.aiDisplayMaster.length=0;t.aiDisplay.length=0}function N(t,e,n){for(var r=-1,i=0,a=t.length;a>i;i++)t[i]==e?r=i:t[i]>e&&t[i]--;-1!=r&&n===o&&t.splice(r,1)}function E(t,e,n,r){var i,a,s=t.aoData[e];if("dom"!==n&&(n&&"auto"!==n||"dom"!==s.src)){var l,u=s.anCells;if(u)for(i=0,a=u.length;a>i;i++){l=u[i];for(;l.childNodes.length;)l.removeChild(l.firstChild);u[i].innerHTML=T(t,e,i,"display")}}else s._aData=j(t,s).data;s._aSortData=null;s._aFilterData=null;var c=t.aoColumns;if(r!==o)c[r].sType=null;else for(i=0,a=c.length;a>i;i++)c[i].sType=null;P(s)}function j(e,n){var r,i,o,a,s=[],l=[],u=n.firstChild,c=0,f=e.aoColumns,h=function(t,e,n){if("string"==typeof t){var r=t.indexOf("@");if(-1!==r){var i=t.substring(r+1);o["@"+i]=n.getAttribute(i)}}},d=function(e){i=f[c];a=t.trim(e.innerHTML);if(i&&i._bAttrSrc){o={display:a};h(i.mData.sort,o,e);h(i.mData.type,o,e);h(i.mData.filter,o,e);s.push(o)}else s.push(a);c++};if(u)for(;u;){r=u.nodeName.toUpperCase();if("TD"==r||"TH"==r){d(u);l.push(u)}u=u.nextSibling}else{l=n.anCells;for(var p=0,g=l.length;g>p;p++)d(l[p])}return{data:s,cells:l}}function I(t,e,n,r){var o,a,s,l,u,c=t.aoData[e],f=c._aData,h=[];if(null===c.nTr){o=n||i.createElement("tr");c.nTr=o;c.anCells=h;o._DT_RowIndex=e;P(c);for(l=0,u=t.aoColumns.length;u>l;l++){s=t.aoColumns[l];a=n?r[l]:i.createElement(s.sCellType);h.push(a);(!n||s.mRender||s.mData!==l)&&(a.innerHTML=T(t,e,l,"display"));s.sClass&&(a.className+=" "+s.sClass);s.bVisible&&!n?o.appendChild(a):!s.bVisible&&n&&a.parentNode.removeChild(a);s.fnCreatedCell&&s.fnCreatedCell.call(t.oInstance,a,T(t,e,l),f,e,l)}ze(t,"aoRowCreatedCallback",null,[o,f,e])}c.nTr.setAttribute("role","row")}function P(e){var n=e.nTr,r=e._aData;if(n){r.DT_RowId&&(n.id=r.DT_RowId);if(r.DT_RowClass){var i=r.DT_RowClass.split(" ");e.__rowc=e.__rowc?vn(e.__rowc.concat(i)):i;t(n).removeClass(e.__rowc.join(" ")).addClass(r.DT_RowClass)}r.DT_RowData&&t(n).data(r.DT_RowData)}}function H(e){var n,r,i,o,a,s=e.nTHead,l=e.nTFoot,u=0===t("th, td",s).length,c=e.oClasses,f=e.aoColumns;u&&(o=t("<tr/>").appendTo(s));for(n=0,r=f.length;r>n;n++){a=f[n];i=t(a.nTh).addClass(a.sClass);u&&i.appendTo(o);if(e.oFeatures.bSort){i.addClass(a.sSortingClass);if(a.bSortable!==!1){i.attr("tabindex",e.iTabIndex).attr("aria-controls",e.sTableId);Ae(e,a.nTh,n)}}a.sTitle!=i.html()&&i.html(a.sTitle);Ue(e,"header")(e,i,a,c)}u&&z(e.aoHeader,s);t(s).find(">tr").attr("role","row");t(s).find(">tr>th, >tr>td").addClass(c.sHeaderTH);t(l).find(">tr>th, >tr>td").addClass(c.sFooterTH);if(null!==l){var h=e.aoFooter[0];for(n=0,r=h.length;r>n;n++){a=f[n];a.nTf=h[n].cell;a.sClass&&t(a.nTf).addClass(a.sClass)}}}function O(e,n,r){var i,a,s,l,u,c,f,h,d,p=[],g=[],m=e.aoColumns.length;if(n){r===o&&(r=!1);for(i=0,a=n.length;a>i;i++){p[i]=n[i].slice();p[i].nTr=n[i].nTr;for(s=m-1;s>=0;s--)e.aoColumns[s].bVisible||r||p[i].splice(s,1);g.push([])}for(i=0,a=p.length;a>i;i++){f=p[i].nTr;if(f)for(;c=f.firstChild;)f.removeChild(c);for(s=0,l=p[i].length;l>s;s++){h=1;d=1;if(g[i][s]===o){f.appendChild(p[i][s].cell);g[i][s]=1;for(;p[i+h]!==o&&p[i][s].cell==p[i+h][s].cell;){g[i+h][s]=1;h++}for(;p[i][s+d]!==o&&p[i][s].cell==p[i][s+d].cell;){for(u=0;h>u;u++)g[i+u][s+d]=1;d++}t(p[i][s].cell).attr("rowspan",h).attr("colspan",d)}}}}}function F(e){var n=ze(e,"aoPreDrawCallback","preDraw",[e]);if(-1===t.inArray(!1,n)){var r=[],i=0,a=e.asStripeClasses,s=a.length,l=(e.aoOpenRows.length,e.oLanguage),u=e.iInitDisplayStart,c="ssp"==Be(e),f=e.aiDisplay;e.bDrawing=!0;if(u!==o&&-1!==u){e._iDisplayStart=c?u:u>=e.fnRecordsDisplay()?0:u;e.iInitDisplayStart=-1}var h=e._iDisplayStart,d=e.fnDisplayEnd();if(e.bDeferLoading){e.bDeferLoading=!1;e.iDraw++;pe(e,!1)}else if(c){if(!e.bDestroying&&!B(e))return}else e.iDraw++;if(0!==f.length)for(var p=c?0:h,g=c?e.aoData.length:d,v=p;g>v;v++){var y=f[v],b=e.aoData[y];null===b.nTr&&I(e,y);var x=b.nTr;if(0!==s){var w=a[i%s];if(b._sRowStripe!=w){t(x).removeClass(b._sRowStripe).addClass(w);b._sRowStripe=w}}ze(e,"aoRowCallback",null,[x,b._aData,i,v]);r.push(x);i++}else{var C=l.sZeroRecords;1==e.iDraw&&"ajax"==Be(e)?C=l.sLoadingRecords:l.sEmptyTable&&0===e.fnRecordsTotal()&&(C=l.sEmptyTable);r[0]=t("<tr/>",{"class":s?a[0]:""}).append(t("<td />",{valign:"top",colSpan:m(e),"class":e.oClasses.sRowEmpty}).html(C))[0]}ze(e,"aoHeaderCallback","header",[t(e.nTHead).children("tr")[0],L(e),h,d,f]);ze(e,"aoFooterCallback","footer",[t(e.nTFoot).children("tr")[0],L(e),h,d,f]);var S=t(e.nTBody);S.children().detach();S.append(t(r));ze(e,"aoDrawCallback","draw",[e]);e.bSorted=!1;e.bFiltered=!1;e.bDrawing=!1}else pe(e,!1)}function R(t,e){var n=t.oFeatures,r=n.bSort,i=n.bFilter;r&&Me(t);i?Y(t,t.oPreviousSearch):t.aiDisplay=t.aiDisplayMaster.slice();e!==!0&&(t._iDisplayStart=0);t._drawHold=e;F(t);t._drawHold=!1}function W(e){var n=e.oClasses,r=t(e.nTable),i=t("<div/>").insertBefore(r),o=e.oFeatures,a=t("<div/>",{id:e.sTableId+"_wrapper","class":n.sWrapper+(e.nTFoot?"":" "+n.sNoFooter)});e.nHolding=i[0];e.nTableWrapper=a[0];e.nTableReinsertBefore=e.nTable.nextSibling;for(var s,l,u,c,f,h,d=e.sDom.split(""),p=0;p<d.length;p++){s=null;l=d[p];if("<"==l){u=t("<div/>")[0];c=d[p+1];if("'"==c||'"'==c){f="";h=2;for(;d[p+h]!=c;){f+=d[p+h];h++}"H"==f?f=n.sJUIHeader:"F"==f&&(f=n.sJUIFooter);if(-1!=f.indexOf(".")){var g=f.split(".");u.id=g[0].substr(1,g[0].length-1);u.className=g[1]}else"#"==f.charAt(0)?u.id=f.substr(1,f.length-1):u.className=f;p+=h}a.append(u);a=t(u)}else if(">"==l)a=a.parent();else if("l"==l&&o.bPaginate&&o.bLengthChange)s=ce(e);else if("f"==l&&o.bFilter)s=$(e);else if("r"==l&&o.bProcessing)s=de(e);else if("t"==l)s=ge(e);else if("i"==l&&o.bInfo)s=ie(e);else if("p"==l&&o.bPaginate)s=fe(e);else if(0!==$e.ext.feature.length)for(var m=$e.ext.feature,v=0,y=m.length;y>v;v++)if(l==m[v].cFeature){s=m[v].fnInit(e);break}if(s){var b=e.aanFeatures;b[l]||(b[l]=[]);b[l].push(s);a.append(s)}}i.replaceWith(a)}function z(e,n){var r,i,o,a,s,l,u,c,f,h,d,p=t(n).children("tr"),g=function(t,e,n){for(var r=t[e];r[n];)n++;return n};e.splice(0,e.length);for(o=0,l=p.length;l>o;o++)e.push([]);for(o=0,l=p.length;l>o;o++){r=p[o];c=0;i=r.firstChild;for(;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase()){f=1*i.getAttribute("colspan");h=1*i.getAttribute("rowspan");f=f&&0!==f&&1!==f?f:1;h=h&&0!==h&&1!==h?h:1;u=g(e,o,c);d=1===f?!0:!1;for(s=0;f>s;s++)for(a=0;h>a;a++){e[o+a][u+s]={cell:i,unique:d};e[o+a].nTr=r}}i=i.nextSibling}}}function q(t,e,n){var r=[];if(!n){n=t.aoHeader;if(e){n=[];z(n,e)}}for(var i=0,o=n.length;o>i;i++)for(var a=0,s=n[i].length;s>a;a++)!n[i][a].unique||r[a]&&t.bSortCellsTop||(r[a]=n[i][a].cell);return r}function U(e,n,r){ze(e,"aoServerParams","serverParams",[n]);if(n&&t.isArray(n)){var i={},o=/(.*?)\[\]$/;t.each(n,function(t,e){var n=e.name.match(o);if(n){var r=n[0];i[r]||(i[r]=[]);i[r].push(e.value)}else i[e.name]=e.value});n=i}var a,s=e.ajax,l=e.oInstance;if(t.isPlainObject(s)&&s.data){a=s.data;var u=t.isFunction(a)?a(n):a;n=t.isFunction(a)&&u?u:t.extend(!0,n,u);delete s.data}var c={data:n,success:function(t){var n=t.error||t.sError;n&&e.oApi._fnLog(e,0,n);e.json=t;ze(e,null,"xhr",[e,t]);r(t)},dataType:"json",cache:!1,type:e.sServerMethod,error:function(t,n){var r=e.oApi._fnLog;"parsererror"==n?r(e,0,"Invalid JSON response",1):4===t.readyState&&r(e,0,"Ajax error",7);pe(e,!1)}};e.oAjaxData=n;ze(e,null,"preXhr",[e,n]);if(e.fnServerData)e.fnServerData.call(l,e.sAjaxSource,t.map(n,function(t,e){return{name:e,value:t}}),r,e);else if(e.sAjaxSource||"string"==typeof s)e.jqXHR=t.ajax(t.extend(c,{url:s||e.sAjaxSource}));else if(t.isFunction(s))e.jqXHR=s.call(l,n,r,e);else{e.jqXHR=t.ajax(t.extend(c,s));s.data=a}}function B(t){if(t.bAjaxDataGet){t.iDraw++;pe(t,!0);U(t,V(t),function(e){X(t,e)});return!1}return!0}function V(e){var n,r,i,o,a=e.aoColumns,s=a.length,l=e.oFeatures,u=e.oPreviousSearch,c=e.aoPreSearchCols,f=[],h=_e(e),d=e._iDisplayStart,p=l.bPaginate!==!1?e._iDisplayLength:-1,g=function(t,e){f.push({name:t,value:e})};g("sEcho",e.iDraw);g("iColumns",s);g("sColumns",dn(a,"sName").join(","));g("iDisplayStart",d);g("iDisplayLength",p);var m={draw:e.iDraw,columns:[],order:[],start:d,length:p,search:{value:u.sSearch,regex:u.bRegex}};for(n=0;s>n;n++){i=a[n];o=c[n];r="function"==typeof i.mData?"function":i.mData;m.columns.push({data:r,name:i.sName,searchable:i.bSearchable,orderable:i.bSortable,search:{value:o.sSearch,regex:o.bRegex}});g("mDataProp_"+n,r);if(l.bFilter){g("sSearch_"+n,o.sSearch);g("bRegex_"+n,o.bRegex);g("bSearchable_"+n,i.bSearchable)}l.bSort&&g("bSortable_"+n,i.bSortable)}if(l.bFilter){g("sSearch",u.sSearch);g("bRegex",u.bRegex)}if(l.bSort){t.each(h,function(t,e){m.order.push({column:e.col,dir:e.dir});g("iSortCol_"+t,e.col);g("sSortDir_"+t,e.dir)});g("iSortingCols",h.length)}var v=$e.ext.legacy.ajax;return null===v?e.sAjaxSource?f:m:v?f:m}function X(t,e){var n=function(t,n){return e[t]!==o?e[t]:e[n]},r=n("sEcho","draw"),i=n("iTotalRecords","recordsTotal"),a=n("iTotalDisplayRecords","recordsFiltered");if(r){if(1*r<t.iDraw)return;t.iDraw=1*r}A(t);t._iRecordsTotal=parseInt(i,10);t._iRecordsDisplay=parseInt(a,10);for(var s=G(t,e),l=0,u=s.length;u>l;l++)x(t,s[l]);t.aiDisplay=t.aiDisplayMaster.slice();t.bAjaxDataGet=!1;F(t);t._bInitComplete||le(t,e);t.bAjaxDataGet=!0;pe(t,!1)}function G(e,n){var r=t.isPlainObject(e.ajax)&&e.ajax.dataSrc!==o?e.ajax.dataSrc:e.sAjaxDataProp;return"data"===r?n.aaData||n[r]:""!==r?M(r)(n):n}function $(e){var n=e.oClasses,r=e.sTableId,o=e.oLanguage,a=e.oPreviousSearch,s=e.aanFeatures,l='<input type="search" class="'+n.sFilterInput+'"/>',u=o.sSearch;u=u.match(/_INPUT_/)?u.replace("_INPUT_",l):u+l;var c=t("<div/>",{id:s.f?null:r+"_filter","class":n.sFilter}).append(t("<label/>").append(u)),f=function(){var t=(s.f,this.value?this.value:"");if(t!=a.sSearch){Y(e,{sSearch:t,bRegex:a.bRegex,bSmart:a.bSmart,bCaseInsensitive:a.bCaseInsensitive});e._iDisplayStart=0;F(e)}},h=t("input",c).val(a.sSearch).attr("placeholder",o.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===Be(e)?be(f,400):f).bind("keypress.DT",function(t){return 13==t.keyCode?!1:void 0}).attr("aria-controls",r);t(e.nTable).on("search.dt.DT",function(t,n){if(e===n)try{h[0]!==i.activeElement&&h.val(a.sSearch)}catch(r){}});return c[0]}function Y(t,e,n){var r=t.oPreviousSearch,i=t.aoPreSearchCols,a=function(t){r.sSearch=t.sSearch;r.bRegex=t.bRegex;r.bSmart=t.bSmart;r.bCaseInsensitive=t.bCaseInsensitive},s=function(t){return t.bEscapeRegex!==o?!t.bEscapeRegex:t.bRegex};y(t);if("ssp"!=Be(t)){Z(t,e.sSearch,n,s(e),e.bSmart,e.bCaseInsensitive);a(e);for(var l=0;l<i.length;l++)K(t,i[l].sSearch,l,s(i[l]),i[l].bSmart,i[l].bCaseInsensitive);J(t)}else a(e);t.bFiltered=!0;ze(t,null,"search",[t])}function J(t){for(var e,n,r=$e.ext.search,i=t.aiDisplay,o=0,a=r.length;a>o;o++){for(var s=[],l=0,u=i.length;u>l;l++){n=i[l];e=t.aoData[n];r[o](t,e._aFilterData,n,e._aData,l)&&s.push(n)}i.length=0;i.push.apply(i,s)}}function K(t,e,n,r,i,o){if(""!==e)for(var a,s=t.aiDisplay,l=Q(e,r,i,o),u=s.length-1;u>=0;u--){a=t.aoData[s[u]]._aFilterData[n];l.test(a)||s.splice(u,1)}}function Z(t,e,n,r,i,o){var a,s,l,u=Q(e,r,i,o),c=t.oPreviousSearch.sSearch,f=t.aiDisplayMaster;0!==$e.ext.search.length&&(n=!0);s=ee(t);if(e.length<=0)t.aiDisplay=f.slice();else{(s||n||c.length>e.length||0!==e.indexOf(c)||t.bSorted)&&(t.aiDisplay=f.slice());a=t.aiDisplay;for(l=a.length-1;l>=0;l--)u.test(t.aoData[a[l]]._sFilterRow)||a.splice(l,1)}}function Q(e,n,r,i){e=n?e:te(e);if(r){var o=t.map(e.match(/"[^"]+"|[^ ]+/g)||"",function(t){return'"'===t.charAt(0)?t.match(/^"(.*)"$/)[1]:t});e="^(?=.*?"+o.join(")(?=.*?")+").*$"}return new RegExp(e,i?"i":"")}function te(t){return t.replace(on,"\\$1")}function ee(t){var e,n,r,i,o,a,s,l,u=t.aoColumns,c=$e.ext.type.search,f=!1;for(n=0,i=t.aoData.length;i>n;n++){l=t.aoData[n];if(!l._aFilterData){a=[];for(r=0,o=u.length;o>r;r++){e=u[r];if(e.bSearchable){s=T(t,n,r,"filter");c[e.sType]&&(s=c[e.sType](s));null===s&&(s="");"string"!=typeof s&&s.toString&&(s=s.toString())}else s="";if(s.indexOf&&-1!==s.indexOf("&")){wn.innerHTML=s;s=Cn?wn.textContent:wn.innerText}s.replace&&(s=s.replace(/[\r\n]/g,""));a.push(s)}l._aFilterData=a;l._sFilterRow=a.join(" ");f=!0}}return f}function ne(t){return{search:t.sSearch,smart:t.bSmart,regex:t.bRegex,caseInsensitive:t.bCaseInsensitive}}function re(t){return{sSearch:t.search,bSmart:t.smart,bRegex:t.regex,bCaseInsensitive:t.caseInsensitive}}function ie(e){var n=e.sTableId,r=e.aanFeatures.i,i=t("<div/>",{"class":e.oClasses.sInfo,id:r?null:n+"_info"});if(!r){e.aoDrawCallback.push({fn:oe,sName:"information"});i.attr("role","status").attr("aria-live","polite");t(e.nTable).attr("aria-describedby",n+"_info")}return i[0]}function oe(e){var n=e.aanFeatures.i;if(0!==n.length){var r=e.oLanguage,i=e._iDisplayStart+1,o=e.fnDisplayEnd(),a=e.fnRecordsTotal(),s=e.fnRecordsDisplay(),l=s?r.sInfo:r.sInfoEmpty;s!==a&&(l+=" "+r.sInfoFiltered);l+=r.sInfoPostFix;l=ae(e,l);var u=r.fnInfoCallback;null!==u&&(l=u.call(e.oInstance,e,i,o,a,s,l));t(n).html(l)}}function ae(t,e){var n=t.fnFormatNumber,r=t._iDisplayStart+1,i=t._iDisplayLength,o=t.fnRecordsDisplay(),a=-1===i;return e.replace(/_START_/g,n.call(t,r)).replace(/_END_/g,n.call(t,t.fnDisplayEnd())).replace(/_MAX_/g,n.call(t,t.fnRecordsTotal())).replace(/_TOTAL_/g,n.call(t,o)).replace(/_PAGE_/g,n.call(t,a?1:Math.ceil(r/i))).replace(/_PAGES_/g,n.call(t,a?1:Math.ceil(o/i)))}function se(t){var e,n,r,i=t.iInitDisplayStart,o=t.aoColumns,a=t.oFeatures;if(t.bInitialised){W(t);H(t);O(t,t.aoHeader);O(t,t.aoFooter);pe(t,!0);a.bAutoWidth&&ye(t);for(e=0,n=o.length;n>e;e++){r=o[e];r.sWidth&&(r.nTh.style.width=Te(r.sWidth))}R(t);var s=Be(t);if("ssp"!=s)if("ajax"==s)U(t,[],function(n){var r=G(t,n);for(e=0;e<r.length;e++)x(t,r[e]);t.iInitDisplayStart=i;R(t);pe(t,!1);le(t,n)},t);else{pe(t,!1);le(t)}}else setTimeout(function(){se(t)},200)}function le(t,e){t._bInitComplete=!0;e&&d(t);ze(t,"aoInitComplete","init",[t,e])}function ue(t,e){var n=parseInt(e,10);t._iDisplayLength=n;qe(t);ze(t,null,"length",[t,n])}function ce(e){for(var n=e.oClasses,r=e.sTableId,i=e.aLengthMenu,o=t.isArray(i[0]),a=o?i[0]:i,s=o?i[1]:i,l=t("<select/>",{name:r+"_length","aria-controls":r,"class":n.sLengthSelect}),u=0,c=a.length;c>u;u++)l[0][u]=new Option(s[u],a[u]);var f=t("<div><label/></div>").addClass(n.sLength);e.aanFeatures.l||(f[0].id=r+"_length");f.children().append(e.oLanguage.sLengthMenu.replace("_MENU_",l[0].outerHTML));t("select",f).val(e._iDisplayLength).bind("change.DT",function(){ue(e,t(this).val());F(e)});t(e.nTable).bind("length.dt.DT",function(n,r,i){e===r&&t("select",f).val(i)});return f[0]}function fe(e){var n=e.sPaginationType,r=$e.ext.pager[n],i="function"==typeof r,o=function(t){F(t)},a=t("<div/>").addClass(e.oClasses.sPaging+n)[0],s=e.aanFeatures;i||r.fnInit(e,a,o);if(!s.p){a.id=e.sTableId+"_paginate";e.aoDrawCallback.push({fn:function(t){if(i){var e,n,a=t._iDisplayStart,l=t._iDisplayLength,u=t.fnRecordsDisplay(),c=-1===l,f=c?0:Math.ceil(a/l),h=c?1:Math.ceil(u/l),d=r(f,h);for(e=0,n=s.p.length;n>e;e++)Ue(t,"pageButton")(t,s.p[e],e,d,f,h)}else r.fnUpdate(t,o)},sName:"pagination"})}return a}function he(t,e,n){var r=t._iDisplayStart,i=t._iDisplayLength,o=t.fnRecordsDisplay();if(0===o||-1===i)r=0;else if("number"==typeof e){r=e*i;r>o&&(r=0)}else if("first"==e)r=0;else if("previous"==e){r=i>=0?r-i:0;0>r&&(r=0)}else"next"==e?o>r+i&&(r+=i):"last"==e?r=Math.floor((o-1)/i)*i:He(t,0,"Unknown paging action: "+e,5);var a=t._iDisplayStart!==r;t._iDisplayStart=r;if(a){ze(t,null,"page",[t]);n&&F(t)}return a}function de(e){return t("<div/>",{id:e.aanFeatures.r?null:e.sTableId+"_processing","class":e.oClasses.sProcessing}).html(e.oLanguage.sProcessing).insertBefore(e.nTable)[0]}function pe(e,n){e.oFeatures.bProcessing&&t(e.aanFeatures.r).css("display",n?"block":"none");ze(e,null,"processing",[e,n])}function ge(e){var n=t(e.nTable);n.attr("role","grid");var r=e.oScroll;if(""===r.sX&&""===r.sY)return e.nTable;var i=r.sX,o=r.sY,a=e.oClasses,s=n.children("caption"),l=s.length?s[0]._captionSide:null,u=t(n[0].cloneNode(!1)),c=t(n[0].cloneNode(!1)),f=n.children("tfoot"),h="<div/>",d=function(t){return t?Te(t):null};r.sX&&"100%"===n.attr("width")&&n.removeAttr("width");f.length||(f=null);var p=t(h,{"class":a.sScrollWrapper}).append(t(h,{"class":a.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:i?d(i):"100%"}).append(t(h,{"class":a.sScrollHeadInner}).css({"box-sizing":"content-box",width:r.sXInner||"100%"}).append(u.removeAttr("id").css("margin-left",0).append(n.children("thead")))).append("top"===l?s:null)).append(t(h,{"class":a.sScrollBody}).css({overflow:"auto",height:d(o),width:d(i)}).append(n));f&&p.append(t(h,{"class":a.sScrollFoot}).css({overflow:"hidden",border:0,width:i?d(i):"100%"}).append(t(h,{"class":a.sScrollFootInner}).append(c.removeAttr("id").css("margin-left",0).append(n.children("tfoot")))).append("bottom"===l?s:null));var g=p.children(),m=g[0],v=g[1],y=f?g[2]:null;i&&t(v).scroll(function(){var t=this.scrollLeft;m.scrollLeft=t;f&&(y.scrollLeft=t)});e.nScrollHead=m;e.nScrollBody=v;e.nScrollFoot=y;e.aoDrawCallback.push({fn:me,sName:"scrolling"});return p[0]}function me(e){var n,r,i,o,a,s,l,u,c,f=e.oScroll,h=f.sX,d=f.sXInner,g=f.sY,m=f.iBarWidth,v=t(e.nScrollHead),y=v[0].style,b=v.children("div"),x=b[0].style,w=b.children("table"),C=e.nScrollBody,S=t(C),T=C.style,k=t(e.nScrollFoot),_=k.children("div"),M=_.children("table"),D=t(e.nTHead),L=t(e.nTable),A=L[0],N=A.style,E=e.nTFoot?t(e.nTFoot):null,j=e.oBrowser,I=j.bScrollOversize,P=[],H=[],O=[],F=function(t){var e=t.style;e.paddingTop="0";e.paddingBottom="0";e.borderTopWidth="0";e.borderBottomWidth="0";e.height=0};L.children("thead, tfoot").remove();a=D.clone().prependTo(L);n=D.find("tr");i=a.find("tr");a.find("th, td").removeAttr("tabindex");if(E){s=E.clone().prependTo(L);r=E.find("tr");o=s.find("tr")}if(!h){T.width="100%";v[0].style.width="100%"}t.each(q(e,a),function(t,n){l=p(e,t);n.style.width=e.aoColumns[l].sWidth});E&&ve(function(t){t.style.width=""},o);f.bCollapse&&""!==g&&(T.height=S[0].offsetHeight+D[0].offsetHeight+"px");c=L.outerWidth();if(""===h){N.width="100%";I&&(L.find("tbody").height()>C.offsetHeight||"scroll"==S.css("overflow-y"))&&(N.width=Te(L.outerWidth()-m))}else if(""!==d)N.width=Te(d);else if(c==S.width()&&S.height()<L.height()){N.width=Te(c-m);L.outerWidth()>c-m&&(N.width=Te(c))}else N.width=Te(c);c=L.outerWidth();ve(F,i);ve(function(e){O.push(e.innerHTML);P.push(Te(t(e).css("width")))},i);ve(function(t,e){t.style.width=P[e]},n);t(i).height(0);if(E){ve(F,o);ve(function(e){H.push(Te(t(e).css("width")))},o);ve(function(t,e){t.style.width=H[e]},r);t(o).height(0)}ve(function(t,e){t.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+O[e]+"</div>";t.style.width=P[e]},i);E&&ve(function(t,e){t.innerHTML="";t.style.width=H[e]},o);if(L.outerWidth()<c){u=C.scrollHeight>C.offsetHeight||"scroll"==S.css("overflow-y")?c+m:c;I&&(C.scrollHeight>C.offsetHeight||"scroll"==S.css("overflow-y"))&&(N.width=Te(u-m));(""===h||""!==d)&&He(e,1,"Possible column misalignment",6)}else u="100%";T.width=Te(u);y.width=Te(u);E&&(e.nScrollFoot.style.width=Te(u));g||I&&(T.height=Te(A.offsetHeight+m));if(g&&f.bCollapse){T.height=Te(g);var R=h&&A.offsetWidth>C.offsetWidth?m:0;A.offsetHeight<C.offsetHeight&&(T.height=Te(A.offsetHeight+R))}var W=L.outerWidth();w[0].style.width=Te(W);x.width=Te(W);var z=L.height()>C.clientHeight||"scroll"==S.css("overflow-y"),U="padding"+(j.bScrollbarLeft?"Left":"Right");x[U]=z?m+"px":"0px";if(E){M[0].style.width=Te(W);_[0].style.width=Te(W);_[0].style[U]=z?m+"px":"0px"}S.scroll();!e.bSorted&&!e.bFiltered||e._drawHold||(C.scrollTop=0)}function ve(t,e,n){for(var r,i,o=0,a=0,s=e.length;s>a;){r=e[a].firstChild;i=n?n[a].firstChild:null;for(;r;){if(1===r.nodeType){n?t(r,i,o):t(r,o);o++}r=r.nextSibling;i=n?i.nextSibling:null}a++}}function ye(e){var r,i,o,a,s,l=e.nTable,u=e.aoColumns,c=e.oScroll,f=c.sY,h=c.sX,p=c.sXInner,g=u.length,y=v(e,"bVisible"),b=t("th",e.nTHead),x=l.getAttribute("width"),w=l.parentNode,C=!1;for(r=0;r<y.length;r++){i=u[y[r]];if(null!==i.sWidth){i.sWidth=xe(i.sWidthOrig,w);C=!0}}if(C||h||f||g!=m(e)||g!=b.length){var S=t(l).clone().empty().css("visibility","hidden").removeAttr("id").append(t(e.nTHead).clone(!1)).append(t(e.nTFoot).clone(!1)).append(t("<tbody><tr/></tbody>"));S.find("tfoot th, tfoot td").css("width","");var T=S.find("tbody tr");b=q(e,S.find("thead")[0]);for(r=0;r<y.length;r++){i=u[y[r]];b[r].style.width=null!==i.sWidthOrig&&""!==i.sWidthOrig?Te(i.sWidthOrig):""}if(e.aoData.length)for(r=0;r<y.length;r++){o=y[r];i=u[o];t(Ce(e,o)).clone(!1).append(i.sContentPadding).appendTo(T)}S.appendTo(w);if(h&&p)S.width(p);else if(h){S.css("width","auto");S.width()<w.offsetWidth&&S.width(w.offsetWidth)}else f?S.width(w.offsetWidth):x&&S.width(x);we(e,S[0]);if(h){var k=0;for(r=0;r<y.length;r++){i=u[y[r]];s=t(b[r]).outerWidth();k+=null===i.sWidthOrig?s:parseInt(i.sWidth,10)+s-t(b[r]).width()}S.width(Te(k));l.style.width=Te(k)}for(r=0;r<y.length;r++){i=u[y[r]];a=t(b[r]).width();a&&(i.sWidth=Te(a))}l.style.width=Te(S.css("width"));S.remove()}else for(r=0;g>r;r++)u[r].sWidth=Te(b.eq(r).width());x&&(l.style.width=Te(x));if((x||h)&&!e._reszEvt){t(n).bind("resize.DT-"+e.sInstance,be(function(){d(e)}));e._reszEvt=!0}}function be(t,e){var n,r,i=e||200;return function(){var e=this,a=+new Date,s=arguments;if(n&&n+i>a){clearTimeout(r);r=setTimeout(function(){n=o;t.apply(e,s)},i)}else if(n){n=a;t.apply(e,s)}else n=a}}function xe(e,n){if(!e)return 0;var r=t("<div/>").css("width",Te(e)).appendTo(n||i.body),o=r[0].offsetWidth;r.remove();return o}function we(e,n){var r=e.oScroll;if(r.sX||r.sY){var i=r.sX?0:r.iBarWidth;n.style.width=Te(t(n).outerWidth()-i)}}function Ce(e,n){var r=Se(e,n);if(0>r)return null;var i=e.aoData[r];return i.nTr?i.anCells[n]:t("<td/>").html(T(e,r,n,"display"))[0]}function Se(t,e){for(var n,r=-1,i=-1,o=0,a=t.aoData.length;a>o;o++){n=T(t,o,e,"display")+"";n=n.replace(Sn,"");if(n.length>r){r=n.length;i=o}}return i}function Te(t){return null===t?"0px":"number"==typeof t?0>t?"0px":t+"px":t.match(/\d$/)?t+"px":t}function ke(){if(!$e.__scrollbarWidth){var e=t("<p/>").css({width:"100%",height:200,padding:0})[0],n=t("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(e).appendTo("body"),r=e.offsetWidth;n.css("overflow","scroll");var i=e.offsetWidth;r===i&&(i=n[0].clientWidth);n.remove();$e.__scrollbarWidth=r-i}return $e.__scrollbarWidth}function _e(e){var n,r,i,o,a,s,l,u=[],c=e.aoColumns,f=e.aaSortingFixed,h=t.isPlainObject(f),d=[],p=function(e){e.length&&!t.isArray(e[0])?d.push(e):d.push.apply(d,e)};t.isArray(f)&&p(f);h&&f.pre&&p(f.pre);p(e.aaSorting);h&&f.post&&p(f.post);for(n=0;n<d.length;n++){l=d[n][0];o=c[l].aDataSort;for(r=0,i=o.length;i>r;r++){a=o[r];s=c[a].sType||"string";u.push({src:l,col:a,dir:d[n][1],index:d[n][2],type:s,formatter:$e.ext.type.order[s+"-pre"]})}}return u}function Me(t){var e,n,r,i,o,a=[],s=$e.ext.type.order,l=t.aoData,u=(t.aoColumns,0),c=t.aiDisplayMaster;y(t);o=_e(t);for(e=0,n=o.length;n>e;e++){i=o[e];i.formatter&&u++;Ee(t,i.col)}if("ssp"!=Be(t)&&0!==o.length){for(e=0,r=c.length;r>e;e++)a[c[e]]=e;c.sort(u===o.length?function(t,e){var n,r,i,s,u,c=o.length,f=l[t]._aSortData,h=l[e]._aSortData;for(i=0;c>i;i++){u=o[i];n=f[u.col];r=h[u.col];s=r>n?-1:n>r?1:0;if(0!==s)return"asc"===u.dir?s:-s}n=a[t];r=a[e];return r>n?-1:n>r?1:0}:function(t,e){var n,r,i,u,c,f,h=o.length,d=l[t]._aSortData,p=l[e]._aSortData; for(i=0;h>i;i++){c=o[i];n=d[c.col];r=p[c.col];f=s[c.type+"-"+c.dir]||s["string-"+c.dir];u=f(n,r);if(0!==u)return u}n=a[t];r=a[e];return r>n?-1:n>r?1:0})}t.bSorted=!0}function De(t){for(var e,n,r=t.aoColumns,i=_e(t),o=t.oLanguage.oAria,a=0,s=r.length;s>a;a++){var l=r[a],u=l.asSorting,c=l.sTitle.replace(/<.*?>/g,""),f=l.nTh;f.removeAttribute("aria-sort");if(l.bSortable){if(i.length>0&&i[0].col==a){f.setAttribute("aria-sort","asc"==i[0].dir?"ascending":"descending");n=u[i[0].index+1]||u[0]}else n=u[0];e=c+("asc"===n?o.sSortAscending:o.sSortDescending)}else e=c;f.setAttribute("aria-label",e)}}function Le(e,n,r,i){var a,s=e.aoColumns[n],l=e.aaSorting,u=s.asSorting,c=function(e){var n=e._idx;n===o&&(n=t.inArray(e[1],u));return n+1>=u.length?0:n+1};"number"==typeof l[0]&&(l=e.aaSorting=[l]);if(r&&e.oFeatures.bSortMulti){var f=t.inArray(n,dn(l,"0"));if(-1!==f){a=c(l[f]);l[f][1]=u[a];l[f]._idx=a}else{l.push([n,u[0],0]);l[l.length-1]._idx=0}}else if(l.length&&l[0][0]==n){a=c(l[0]);l.length=1;l[0][1]=u[a];l[0]._idx=a}else{l.length=0;l.push([n,u[0]]);l[0]._idx=0}R(e);"function"==typeof i&&i(e)}function Ae(t,e,n,r){var i=t.aoColumns[n];Re(e,{},function(e){if(i.bSortable!==!1)if(t.oFeatures.bProcessing){pe(t,!0);setTimeout(function(){Le(t,n,e.shiftKey,r);"ssp"!==Be(t)&&pe(t,!1)},0)}else Le(t,n,e.shiftKey,r)})}function Ne(e){var n,r,i,o=e.aLastSort,a=e.oClasses.sSortColumn,s=_e(e),l=e.oFeatures;if(l.bSort&&l.bSortClasses){for(n=0,r=o.length;r>n;n++){i=o[n].src;t(dn(e.aoData,"anCells",i)).removeClass(a+(2>n?n+1:3))}for(n=0,r=s.length;r>n;n++){i=s[n].src;t(dn(e.aoData,"anCells",i)).addClass(a+(2>n?n+1:3))}}e.aLastSort=s}function Ee(t,e){var n,r=t.aoColumns[e],i=$e.ext.order[r.sSortDataType];i&&(n=i.call(t.oInstance,t,e,g(t,e)));for(var o,a,s=$e.ext.type.order[r.sType+"-pre"],l=0,u=t.aoData.length;u>l;l++){o=t.aoData[l];o._aSortData||(o._aSortData=[]);if(!o._aSortData[e]||i){a=i?n[l]:T(t,l,e,"sort");o._aSortData[e]=s?s(a):a}}}function je(e){if(e.oFeatures.bStateSave&&!e.bDestroying){var n={time:+new Date,start:e._iDisplayStart,length:e._iDisplayLength,order:t.extend(!0,[],e.aaSorting),search:ne(e.oPreviousSearch),columns:t.map(e.aoColumns,function(t,n){return{visible:t.bVisible,search:ne(e.aoPreSearchCols[n])}})};ze(e,"aoStateSaveParams","stateSaveParams",[e,n]);e.oSavedState=n;e.fnStateSaveCallback.call(e.oInstance,e,n)}}function Ie(e){var n,r,i=e.aoColumns;if(e.oFeatures.bStateSave){var o=e.fnStateLoadCallback.call(e.oInstance,e);if(o&&o.time){var a=ze(e,"aoStateLoadParams","stateLoadParams",[e,o]);if(-1===t.inArray(!1,a)){var s=e.iStateDuration;if(!(s>0&&o.time<+new Date-1e3*s)&&i.length===o.columns.length){e.oLoadedState=t.extend(!0,{},o);e._iDisplayStart=o.start;e.iInitDisplayStart=o.start;e._iDisplayLength=o.length;e.aaSorting=[];t.each(o.order,function(t,n){e.aaSorting.push(n[0]>=i.length?[0,n[1]]:n)});t.extend(e.oPreviousSearch,re(o.search));for(n=0,r=o.columns.length;r>n;n++){var l=o.columns[n];i[n].bVisible=l.visible;t.extend(e.aoPreSearchCols[n],re(l.search))}ze(e,"aoStateLoaded","stateLoaded",[e,o])}}}}}function Pe(e){var n=$e.settings,r=t.inArray(e,dn(n,"nTable"));return-1!==r?n[r]:null}function He(t,e,r,i){r="DataTables warning: "+(null!==t?"table id="+t.sTableId+" - ":"")+r;i&&(r+=". For more information about this error, please see http://datatables.net/tn/"+i);if(e)n.console&&console.log&&console.log(r);else{var o=$e.ext,a=o.sErrMode||o.errMode;if("alert"!=a)throw new Error(r);alert(r)}}function Oe(e,n,r,i){if(t.isArray(r))t.each(r,function(r,i){t.isArray(i)?Oe(e,n,i[0],i[1]):Oe(e,n,i)});else{i===o&&(i=r);n[r]!==o&&(e[i]=n[r])}}function Fe(e,n,r){var i;for(var o in n)if(n.hasOwnProperty(o)){i=n[o];if(t.isPlainObject(i)){t.isPlainObject(e[o])||(e[o]={});t.extend(!0,e[o],i)}else e[o]=r&&"data"!==o&&"aaData"!==o&&t.isArray(i)?i.slice():i}return e}function Re(e,n,r){t(e).bind("click.DT",n,function(t){e.blur();r(t)}).bind("keypress.DT",n,function(t){if(13===t.which){t.preventDefault();r(t)}}).bind("selectstart.DT",function(){return!1})}function We(t,e,n,r){n&&t[e].push({fn:n,sName:r})}function ze(e,n,r,i){var o=[];n&&(o=t.map(e[n].slice().reverse(),function(t){return t.fn.apply(e.oInstance,i)}));null!==r&&t(e.nTable).trigger(r+".dt",i);return o}function qe(t){var e=t._iDisplayStart,n=t.fnDisplayEnd(),r=t._iDisplayLength;n===t.fnRecordsDisplay()&&(e=n-r);(-1===r||0>e)&&(e=0);t._iDisplayStart=e}function Ue(e,n){var r=e.renderer,i=$e.ext.renderer[n];return t.isPlainObject(r)&&r[n]?i[r[n]]||i._:"string"==typeof r?i[r]||i._:i._}function Be(t){return t.oFeatures.bServerSide?"ssp":t.ajax||t.sAjaxSource?"ajax":"dom"}function Ve(t,e){var n=[],r=Vn.numbers_length,i=Math.floor(r/2);if(r>=e)n=gn(0,e);else if(i>=t){n=gn(0,r-2);n.push("ellipsis");n.push(e-1)}else if(t>=e-1-i){n=gn(e-(r-2),e);n.splice(0,0,"ellipsis");n.splice(0,0,0)}else{n=gn(t-1,t+2);n.push("ellipsis");n.push(e-1);n.splice(0,0,"ellipsis");n.splice(0,0,0)}n.DT_el="span";return n}function Xe(e){t.each({num:function(t){return Xn(t,e)},"num-fmt":function(t){return Xn(t,e,an)},"html-num":function(t){return Xn(t,e,en)},"html-num-fmt":function(t){return Xn(t,e,en,an)}},function(t,n){Ye.type.order[t+e+"-pre"]=n})}function Ge(t){return function(){var e=[Pe(this[$e.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return $e.ext.internal[t].apply(this,e)}}var $e,Ye,Je,Ke,Ze,Qe={},tn=/[\r\n]/g,en=/<.*?>/g,nn=/^[\w\+\-]/,rn=/[\w\+\-]$/,on=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g"),an=/[',$£€¥%\u2009\u202F]/g,sn=function(t){return t&&t!==!0&&"-"!==t?!1:!0},ln=function(t){var e=parseInt(t,10);return!isNaN(e)&&isFinite(t)?e:null},un=function(t,e){Qe[e]||(Qe[e]=new RegExp(te(e),"g"));return"string"==typeof t?t.replace(/\./g,"").replace(Qe[e],"."):t},cn=function(t,e,n){var r="string"==typeof t;e&&r&&(t=un(t,e));n&&r&&(t=t.replace(an,""));return sn(t)||!isNaN(parseFloat(t))&&isFinite(t)},fn=function(t){return sn(t)||"string"==typeof t},hn=function(t,e,n){if(sn(t))return!0;var r=fn(t);return r&&cn(mn(t),e,n)?!0:null},dn=function(t,e,n){var r=[],i=0,a=t.length;if(n!==o)for(;a>i;i++)t[i]&&t[i][e]&&r.push(t[i][e][n]);else for(;a>i;i++)t[i]&&r.push(t[i][e]);return r},pn=function(t,e,n,r){var i=[],a=0,s=e.length;if(r!==o)for(;s>a;a++)i.push(t[e[a]][n][r]);else for(;s>a;a++)i.push(t[e[a]][n]);return i},gn=function(t,e){var n,r=[];if(e===o){e=0;n=t}else{n=e;e=t}for(var i=e;n>i;i++)r.push(i);return r},mn=function(t){return t.replace(en,"")},vn=function(t){var e,n,r,i=[],o=t.length,a=0;t:for(n=0;o>n;n++){e=t[n];for(r=0;a>r;r++)if(i[r]===e)continue t;i.push(e);a++}return i},yn=function(t,e,n){t[e]!==o&&(t[n]=t[e])},bn=/\[.*?\]$/,xn=/\(\)$/,wn=t("<div>")[0],Cn=wn.textContent!==o,Sn=/<.*?>/g;$e=function(e){this.$=function(t,e){return this.api(!0).$(t,e)};this._=function(t,e){return this.api(!0).rows(t,e).data()};this.api=function(t){return new Je(t?Pe(this[Ye.iApiIndex]):this)};this.fnAddData=function(e,n){var r=this.api(!0),i=t.isArray(e)&&(t.isArray(e[0])||t.isPlainObject(e[0]))?r.rows.add(e):r.row.add(e);(n===o||n)&&r.draw();return i.flatten().toArray()};this.fnAdjustColumnSizing=function(t){var e=this.api(!0).columns.adjust(),n=e.settings()[0],r=n.oScroll;t===o||t?e.draw(!1):(""!==r.sX||""!==r.sY)&&me(n)};this.fnClearTable=function(t){var e=this.api(!0).clear();(t===o||t)&&e.draw()};this.fnClose=function(t){this.api(!0).row(t).child.hide()};this.fnDeleteRow=function(t,e,n){var r=this.api(!0),i=r.rows(t),a=i.settings()[0],s=a.aoData[i[0][0]];i.remove();e&&e.call(this,a,s);(n===o||n)&&r.draw();return s};this.fnDestroy=function(t){this.api(!0).destroy(t)};this.fnDraw=function(t){this.api(!0).draw(!t)};this.fnFilter=function(t,e,n,r,i,a){var s=this.api(!0);null===e||e===o?s.search(t,n,r,a):s.column(e).search(t,n,r,a);s.draw()};this.fnGetData=function(t,e){var n=this.api(!0);if(t!==o){var r=t.nodeName?t.nodeName.toLowerCase():"";return e!==o||"td"==r||"th"==r?n.cell(t,e).data():n.row(t).data()||null}return n.data().toArray()};this.fnGetNodes=function(t){var e=this.api(!0);return t!==o?e.row(t).node():e.rows().nodes().flatten().toArray()};this.fnGetPosition=function(t){var e=this.api(!0),n=t.nodeName.toUpperCase();if("TR"==n)return e.row(t).index();if("TD"==n||"TH"==n){var r=e.cell(t).index();return[r.row,r.columnVisible,r.column]}return null};this.fnIsOpen=function(t){return this.api(!0).row(t).child.isShown()};this.fnOpen=function(t,e,n){return this.api(!0).row(t).child(e,n).show().child()[0]};this.fnPageChange=function(t,e){var n=this.api(!0).page(t);(e===o||e)&&n.draw(!1)};this.fnSetColumnVis=function(t,e,n){var r=this.api(!0).column(t).visible(e);(n===o||n)&&r.columns.adjust().draw()};this.fnSettings=function(){return Pe(this[Ye.iApiIndex])};this.fnSort=function(t){this.api(!0).order(t).draw()};this.fnSortListener=function(t,e,n){this.api(!0).order.listener(t,e,n)};this.fnUpdate=function(t,e,n,r,i){var a=this.api(!0);n===o||null===n?a.row(e).data(t):a.cell(e,n).data(t);(i===o||i)&&a.columns.adjust();(r===o||r)&&a.draw();return 0};this.fnVersionCheck=Ye.fnVersionCheck;var n=this,i=e===o,c=this.length;i&&(e={});this.oApi=this.internal=Ye.internal;for(var d in $e.ext.internal)d&&(this[d]=Ge(d));this.each(function(){var d,p={},g=c>1?Fe(p,e,!0):e,m=0,v=this.getAttribute("id"),y=!1,C=$e.defaults;if("table"==this.nodeName.toLowerCase()){s(C);l(C.column);r(C,C,!0);r(C.column,C.column,!0);r(C,g);var S=$e.settings;for(m=0,d=S.length;d>m;m++){if(S[m].nTable==this){var T=g.bRetrieve!==o?g.bRetrieve:C.bRetrieve,k=g.bDestroy!==o?g.bDestroy:C.bDestroy;if(i||T)return S[m].oInstance;if(k){S[m].oInstance.fnDestroy();break}He(S[m],0,"Cannot reinitialise DataTable",3);return}if(S[m].sTableId==this.id){S.splice(m,1);break}}if(null===v||""===v){v="DataTables_Table_"+$e.ext._unique++;this.id=v}var _=t.extend(!0,{},$e.models.oSettings,{nTable:this,oApi:n.internal,oInit:g,sDestroyWidth:t(this)[0].style.width,sInstance:v,sTableId:v});S.push(_);_.oInstance=1===n.length?n:t(this).dataTable();s(g);g.oLanguage&&a(g.oLanguage);g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=t.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]);g=Fe(t.extend(!0,{},C),g);Oe(_.oFeatures,g,["bPaginate","bLengthChange","bFilter","bSort","bSortMulti","bInfo","bProcessing","bAutoWidth","bSortClasses","bServerSide","bDeferRender"]);Oe(_,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);Oe(_.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);Oe(_.oLanguage,g,"fnInfoCallback");We(_,"aoDrawCallback",g.fnDrawCallback,"user");We(_,"aoServerParams",g.fnServerParams,"user");We(_,"aoStateSaveParams",g.fnStateSaveParams,"user");We(_,"aoStateLoadParams",g.fnStateLoadParams,"user");We(_,"aoStateLoaded",g.fnStateLoaded,"user");We(_,"aoRowCallback",g.fnRowCallback,"user");We(_,"aoRowCreatedCallback",g.fnCreatedRow,"user");We(_,"aoHeaderCallback",g.fnHeaderCallback,"user");We(_,"aoFooterCallback",g.fnFooterCallback,"user");We(_,"aoInitComplete",g.fnInitComplete,"user");We(_,"aoPreDrawCallback",g.fnPreDrawCallback,"user");var M=_.oClasses;if(g.bJQueryUI){t.extend(M,$e.ext.oJUIClasses,g.oClasses);g.sDom===C.sDom&&"lfrtip"===C.sDom&&(_.sDom='<"H"lfr>t<"F"ip>');_.renderer?t.isPlainObject(_.renderer)&&!_.renderer.header&&(_.renderer.header="jqueryui"):_.renderer="jqueryui"}else t.extend(M,$e.ext.classes,g.oClasses);t(this).addClass(M.sTable);(""!==_.oScroll.sX||""!==_.oScroll.sY)&&(_.oScroll.iBarWidth=ke());_.oScroll.sX===!0&&(_.oScroll.sX="100%");if(_.iInitDisplayStart===o){_.iInitDisplayStart=g.iDisplayStart;_._iDisplayStart=g.iDisplayStart}if(null!==g.iDeferLoading){_.bDeferLoading=!0;var D=t.isArray(g.iDeferLoading);_._iRecordsDisplay=D?g.iDeferLoading[0]:g.iDeferLoading;_._iRecordsTotal=D?g.iDeferLoading[1]:g.iDeferLoading}if(""!==g.oLanguage.sUrl){_.oLanguage.sUrl=g.oLanguage.sUrl;t.getJSON(_.oLanguage.sUrl,null,function(e){a(e);r(C.oLanguage,e);t.extend(!0,_.oLanguage,g.oLanguage,e);se(_)});y=!0}else t.extend(!0,_.oLanguage,g.oLanguage);null===g.asStripeClasses&&(_.asStripeClasses=[M.sStripeOdd,M.sStripeEven]);var L=_.asStripeClasses,A=t("tbody tr:eq(0)",this);if(-1!==t.inArray(!0,t.map(L,function(t){return A.hasClass(t)}))){t("tbody tr",this).removeClass(L.join(" "));_.asDestroyStripes=L.slice()}var N,E=[],I=this.getElementsByTagName("thead");if(0!==I.length){z(_.aoHeader,I[0]);E=q(_)}if(null===g.aoColumns){N=[];for(m=0,d=E.length;d>m;m++)N.push(null)}else N=g.aoColumns;for(m=0,d=N.length;d>m;m++)f(_,E?E[m]:null);b(_,g.aoColumnDefs,N,function(t,e){h(_,t,e)});if(A.length){var P=function(t,e){return t.getAttribute("data-"+e)?e:null};t.each(j(_,A[0]).cells,function(t,e){var n=_.aoColumns[t];if(n.mData===t){var r=P(e,"sort")||P(e,"order"),i=P(e,"filter")||P(e,"search");if(null!==r||null!==i){n.mData={_:t+".display",sort:null!==r?t+".@data-"+r:o,type:null!==r?t+".@data-"+r:o,filter:null!==i?t+".@data-"+i:o};h(_,t)}}})}var H=_.oFeatures;if(g.bStateSave){H.bStateSave=!0;Ie(_,g);We(_,"aoDrawCallback",je,"state_save")}if(g.aaSorting===o){var O=_.aaSorting;for(m=0,d=O.length;d>m;m++)O[m][1]=_.aoColumns[m].asSorting[0]}Ne(_);H.bSort&&We(_,"aoDrawCallback",function(){if(_.bSorted){var e=_e(_),n={};t.each(e,function(t,e){n[e.src]=e.dir});ze(_,null,"order",[_,e,n]);De(_)}});We(_,"aoDrawCallback",function(){(_.bSorted||"ssp"===Be(_)||H.bDeferRender)&&Ne(_)},"sc");u(_);var F=t(this).children("caption").each(function(){this._captionSide=t(this).css("caption-side")}),R=t(this).children("thead");0===R.length&&(R=t("<thead/>").appendTo(this));_.nTHead=R[0];var W=t(this).children("tbody");0===W.length&&(W=t("<tbody/>").appendTo(this));_.nTBody=W[0];var U=t(this).children("tfoot");0===U.length&&F.length>0&&(""!==_.oScroll.sX||""!==_.oScroll.sY)&&(U=t("<tfoot/>").appendTo(this));if(0===U.length||0===U.children().length)t(this).addClass(M.sNoFooter);else if(U.length>0){_.nTFoot=U[0];z(_.aoFooter,_.nTFoot)}if(g.aaData)for(m=0;m<g.aaData.length;m++)x(_,g.aaData[m]);else(_.bDeferLoading||"dom"==Be(_))&&w(_,t(_.nTBody).children("tr"));_.aiDisplay=_.aiDisplayMaster.slice();_.bInitialised=!0;y===!1&&se(_)}else He(null,0,"Non-table node initialisation ("+this.nodeName+")",2)});n=null;return this};var Tn=[],kn=Array.prototype,_n=function(e){var n,r,i=$e.settings,o=t.map(i,function(t){return t.nTable});if(!e)return[];if(e.nTable&&e.oApi)return[e];if(e.nodeName&&"table"===e.nodeName.toLowerCase()){n=t.inArray(e,o);return-1!==n?[i[n]]:null}if(e&&"function"==typeof e.settings)return e.settings().toArray();"string"==typeof e?r=t(e):e instanceof t&&(r=e);return r?r.map(function(){n=t.inArray(this,o);return-1!==n?i[n]:null}).toArray():void 0};Je=function(e,n){if(!this instanceof Je)throw"DT API must be constructed as a new object";var r=[],i=function(t){var e=_n(t);e&&r.push.apply(r,e)};if(t.isArray(e))for(var o=0,a=e.length;a>o;o++)i(e[o]);else i(e);this.context=vn(r);n&&this.push.apply(this,n.toArray?n.toArray():n);this.selector={rows:null,cols:null,opts:null};Je.extend(this,this,Tn)};$e.Api=Je;Je.prototype={concat:kn.concat,context:[],each:function(t){for(var e=0,n=this.length;n>e;e++)t.call(this,this[e],e,this);return this},eq:function(t){var e=this.context;return e.length>t?new Je(e[t],this[t]):null},filter:function(t){var e=[];if(kn.filter)e=kn.filter.call(this,t,this);else for(var n=0,r=this.length;r>n;n++)t.call(this,this[n],n,this)&&e.push(this[n]);return new Je(this.context,e)},flatten:function(){var t=[];return new Je(this.context,t.concat.apply(t,this.toArray()))},join:kn.join,indexOf:kn.indexOf||function(t,e){for(var n=e||0,r=this.length;r>n;n++)if(this[n]===t)return n;return-1},iterator:function(t,e,n){var r,i,a,s,l,u,c,f,h=[],d=this.context,p=this.selector;if("string"==typeof t){n=e;e=t;t=!1}for(i=0,a=d.length;a>i;i++)if("table"===e){r=n(d[i],i);r!==o&&h.push(r)}else if("columns"===e||"rows"===e){r=n(d[i],this[i],i);r!==o&&h.push(r)}else if("column"===e||"column-rows"===e||"row"===e||"cell"===e){c=this[i];"column-rows"===e&&(u=En(d[i],p.opts));for(s=0,l=c.length;l>s;s++){f=c[s];r="cell"===e?n(d[i],f.row,f.column,i,s):n(d[i],f,i,s,u);r!==o&&h.push(r)}}if(h.length){var g=new Je(d,t?h.concat.apply([],h):h),m=g.selector;m.rows=p.rows;m.cols=p.cols;m.opts=p.opts;return g}return this},lastIndexOf:kn.lastIndexOf||function(){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(t){var e=[];if(kn.map)e=kn.map.call(this,t,this);else for(var n=0,r=this.length;r>n;n++)e.push(t.call(this,this[n],n));return new Je(this.context,e)},pluck:function(t){return this.map(function(e){return e[t]})},pop:kn.pop,push:kn.push,reduce:kn.reduce||function(t,e){return c(this,t,e,0,this.length,1)},reduceRight:kn.reduceRight||function(t,e){return c(this,t,e,this.length-1,-1,-1)},reverse:kn.reverse,selector:null,shift:kn.shift,sort:kn.sort,splice:kn.splice,toArray:function(){return kn.slice.call(this)},to$:function(){return t(this)},toJQuery:function(){return t(this)},unique:function(){return new Je(this.context,vn(this))},unshift:kn.unshift};Je.extend=function(e,n,r){if(n&&(n instanceof Je||n.__dt_wrapper)){var i,o,a,s=function(t,e,n){return function(){var r=e.apply(t,arguments);Je.extend(r,r,n.methodExt);return r}};for(i=0,o=r.length;o>i;i++){a=r[i];n[a.name]="function"==typeof a.val?s(e,a.val,a):t.isPlainObject(a.val)?{}:a.val;n[a.name].__dt_wrapper=!0;Je.extend(e,n[a.name],a.propExt)}}};Je.register=Ke=function(e,n){if(t.isArray(e))for(var r=0,i=e.length;i>r;r++)Je.register(e[r],n);else{var o,a,s,l,u=e.split("."),c=Tn,f=function(t,e){for(var n=0,r=t.length;r>n;n++)if(t[n].name===e)return t[n];return null};for(o=0,a=u.length;a>o;o++){l=-1!==u[o].indexOf("()");s=l?u[o].replace("()",""):u[o];var h=f(c,s);if(!h){h={name:s,val:{},methodExt:[],propExt:[]};c.push(h)}o===a-1?h.val=n:c=l?h.methodExt:h.propExt}}};Je.registerPlural=Ze=function(e,n,r){Je.register(e,r);Je.register(n,function(){var e=r.apply(this,arguments);return e===this?this:e instanceof Je?e.length?t.isArray(e[0])?new Je(e.context,e[0]):e[0]:o:e})};var Mn=function(e,n){if("number"==typeof e)return[n[e]];var r=t.map(n,function(t){return t.nTable});return t(r).filter(e).map(function(){var e=t.inArray(this,r);return n[e]}).toArray()};Ke("tables()",function(t){return t?new Je(Mn(t,this.context)):this});Ke("table()",function(t){var e=this.tables(t),n=e.context;return n.length?new Je(n[0]):e});Ze("tables().nodes()","table().node()",function(){return this.iterator("table",function(t){return t.nTable})});Ze("tables().body()","table().body()",function(){return this.iterator("table",function(t){return t.nTBody})});Ze("tables().header()","table().header()",function(){return this.iterator("table",function(t){return t.nTHead})});Ze("tables().footer()","table().footer()",function(){return this.iterator("table",function(t){return t.nTFoot})});Ze("tables().containers()","table().container()",function(){return this.iterator("table",function(t){return t.nTableWrapper})});Ke("draw()",function(t){return this.iterator("table",function(e){R(e,t===!1)})});Ke("page()",function(t){return t===o?this.page.info().page:this.iterator("table",function(e){he(e,t)})});Ke("page.info()",function(){if(0===this.context.length)return o;var t=this.context[0],e=t._iDisplayStart,n=t._iDisplayLength,r=t.fnRecordsDisplay(),i=-1===n;return{page:i?0:Math.floor(e/n),pages:i?1:Math.ceil(r/n),start:e,end:t.fnDisplayEnd(),length:n,recordsTotal:t.fnRecordsTotal(),recordsDisplay:r}});Ke("page.len()",function(t){return t===o?0!==this.context.length?this.context[0]._iDisplayLength:o:this.iterator("table",function(e){ue(e,t)})});var Dn=function(t,e,n){if("ssp"==Be(t))R(t,e);else{pe(t,!0);U(t,[],function(n){A(t);for(var r=G(t,n),i=0,o=r.length;o>i;i++)x(t,r[i]);R(t,e);pe(t,!1)})}if(n){var r=new Je(t);r.one("draw",function(){n(r.ajax.json())})}};Ke("ajax.json()",function(){var t=this.context;return t.length>0?t[0].json:void 0});Ke("ajax.params()",function(){var t=this.context;return t.length>0?t[0].oAjaxData:void 0});Ke("ajax.reload()",function(t,e){return this.iterator("table",function(n){Dn(n,e===!1,t)})});Ke("ajax.url()",function(e){var n=this.context;if(e===o){if(0===n.length)return o;n=n[0];return n.ajax?t.isPlainObject(n.ajax)?n.ajax.url:n.ajax:n.sAjaxSource}return this.iterator("table",function(n){t.isPlainObject(n.ajax)?n.ajax.url=e:n.ajax=e})});Ke("ajax.url().load()",function(t,e){return this.iterator("table",function(n){Dn(n,e===!1,t)})});var Ln=function(e,n){var r,i,a,s,l,u,c=[];e&&"string"!=typeof e&&e.length!==o||(e=[e]);for(a=0,s=e.length;s>a;a++){i=e[a]&&e[a].split?e[a].split(","):[e[a]];for(l=0,u=i.length;u>l;l++){r=n("string"==typeof i[l]?t.trim(i[l]):i[l]);r&&r.length&&c.push.apply(c,r)}}return c},An=function(t){t||(t={});t.filter&&!t.search&&(t.search=t.filter);return{search:t.search||"none",order:t.order||"current",page:t.page||"all"}},Nn=function(t){for(var e=0,n=t.length;n>e;e++)if(t[e].length>0){t[0]=t[e];t.length=1;t.context=[t.context[e]];return t}t.length=0;return t},En=function(e,n){var r,i,o,a=[],s=e.aiDisplay,l=e.aiDisplayMaster,u=n.search,c=n.order,f=n.page;if("ssp"==Be(e))return"removed"===u?[]:gn(0,l.length);if("current"==f)for(r=e._iDisplayStart,i=e.fnDisplayEnd();i>r;r++)a.push(s[r]);else if("current"==c||"applied"==c)a="none"==u?l.slice():"applied"==u?s.slice():t.map(l,function(e){return-1===t.inArray(e,s)?e:null});else if("index"==c||"original"==c)for(r=0,i=e.aoData.length;i>r;r++)if("none"==u)a.push(r);else{o=t.inArray(r,s);(-1===o&&"removed"==u||o>=0&&"applied"==u)&&a.push(r)}return a},jn=function(e,n,r){return Ln(n,function(n){var i=ln(n);if(null!==i&&!r)return[i];var o=En(e,r);if(null!==i&&-1!==t.inArray(i,o))return[i];if(!n)return o;for(var a=[],s=0,l=o.length;l>s;s++)a.push(e.aoData[o[s]].nTr);return n.nodeName&&-1!==t.inArray(n,a)?[n._DT_RowIndex]:t(a).filter(n).map(function(){return this._DT_RowIndex}).toArray()})};Ke("rows()",function(e,n){if(e===o)e="";else if(t.isPlainObject(e)){n=e;e=""}n=An(n);var r=this.iterator("table",function(t){return jn(t,e,n)});r.selector.rows=e;r.selector.opts=n;return r});Ke("rows().nodes()",function(){return this.iterator("row",function(t,e){return t.aoData[e].nTr||o})});Ke("rows().data()",function(){return this.iterator(!0,"rows",function(t,e){return pn(t.aoData,e,"_aData")})});Ze("rows().cache()","row().cache()",function(t){return this.iterator("row",function(e,n){var r=e.aoData[n];return"search"===t?r._aFilterData:r._aSortData})});Ze("rows().invalidate()","row().invalidate()",function(t){return this.iterator("row",function(e,n){E(e,n,t)})});Ze("rows().indexes()","row().index()",function(){return this.iterator("row",function(t,e){return e})});Ze("rows().remove()","row().remove()",function(){var e=this;return this.iterator("row",function(n,r,i){var o=n.aoData;o.splice(r,1);for(var a=0,s=o.length;s>a;a++)null!==o[a].nTr&&(o[a].nTr._DT_RowIndex=a);t.inArray(r,n.aiDisplay);N(n.aiDisplayMaster,r);N(n.aiDisplay,r);N(e[i],r,!1);qe(n)})});Ke("rows.add()",function(t){var e=this.iterator("table",function(e){var n,r,i,o=[];for(r=0,i=t.length;i>r;r++){n=t[r];o.push(n.nodeName&&"TR"===n.nodeName.toUpperCase()?w(e,n)[0]:x(e,n))}return o}),n=this.rows(-1);n.pop();n.push.apply(n,e.toArray());return n});Ke("row()",function(t,e){return Nn(this.rows(t,e))});Ke("row().data()",function(t){var e=this.context;if(t===o)return e.length&&this.length?e[0].aoData[this[0]]._aData:o;e[0].aoData[this[0]]._aData=t;E(e[0],this[0],"data");return this});Ke("row().node()",function(){var t=this.context;return t.length&&this.length?t[0].aoData[this[0]].nTr||null:null});Ke("row.add()",function(e){e instanceof t&&e.length&&(e=e[0]);var n=this.iterator("table",function(t){return e.nodeName&&"TR"===e.nodeName.toUpperCase()?w(t,e)[0]:x(t,e)});return this.row(n[0])});var In=function(e,n,r,i){var o=[],a=function(n,r){if(n.nodeName&&"tr"===n.nodeName.toLowerCase())o.push(n);else{var i=t("<tr><td/></tr>").addClass(r);t("td",i).addClass(r).html(n)[0].colSpan=m(e);o.push(i[0])}};if(t.isArray(r)||r instanceof t)for(var s=0,l=r.length;l>s;s++)a(r[s],i);else a(r,i);n._details&&n._details.remove();n._details=t(o);n._detailsShow&&n._details.insertAfter(n.nTr)},Pn=function(t){var e=t.context;if(e.length&&t.length){var n=e[0].aoData[t[0]];if(n._details){n._details.remove();n._detailsShow=o;n._details=o}}},Hn=function(t,e){var n=t.context;if(n.length&&t.length){var r=n[0].aoData[t[0]];if(r._details){r._detailsShow=e;e?r._details.insertAfter(r.nTr):r._details.detach();On(n[0])}}},On=function(t){var e=new Je(t),n=".dt.DT_details",r="draw"+n,i="column-visibility"+n,o="destroy"+n,a=t.aoData;e.off(r+" "+i+" "+o);if(dn(a,"_details").length>0){e.on(r,function(n,r){t===r&&e.rows({page:"current"}).eq(0).each(function(t){var e=a[t];e._detailsShow&&e._details.insertAfter(e.nTr)})});e.on(i,function(e,n){if(t===n)for(var r,i=m(n),o=0,s=a.length;s>o;o++){r=a[o];r._details&&r._details.children("td[colspan]").attr("colspan",i)}});e.on(o,function(e,n){if(t===n)for(var r=0,i=a.length;i>r;r++)a[r]._details&&Pn(a[r])})}},Fn="",Rn=Fn+"row().child",Wn=Rn+"()";Ke(Wn,function(t,e){var n=this.context;if(t===o)return n.length&&this.length?n[0].aoData[this[0]]._details:o;t===!0?this.child.show():t===!1?Pn(this):n.length&&this.length&&In(n[0],n[0].aoData[this[0]],t,e);return this});Ke([Rn+".show()",Wn+".show()"],function(){Hn(this,!0);return this});Ke([Rn+".hide()",Wn+".hide()"],function(){Hn(this,!1);return this});Ke([Rn+".remove()",Wn+".remove()"],function(){Pn(this);return this});Ke(Rn+".isShown()",function(){var t=this.context;return t.length&&this.length?t[0].aoData[this[0]]._detailsShow||!1:!1});var zn=/^(.+):(name|visIdx|visible)$/,qn=function(e,n){var r=e.aoColumns,i=dn(r,"sName"),o=dn(r,"nTh");return Ln(n,function(n){var a=ln(n);if(""===n)return gn(r.length);if(null!==a)return[a>=0?a:r.length+a];var s="string"==typeof n?n.match(zn):"";if(!s)return t(o).filter(n).map(function(){return t.inArray(this,o)}).toArray();switch(s[2]){case"visIdx":case"visible":var l=parseInt(s[1],10);if(0>l){var u=t.map(r,function(t,e){return t.bVisible?e:null});return[u[u.length+l]]}return[p(e,l)];case"name":return t.map(i,function(t,e){return t===s[1]?e:null})}})},Un=function(e,n,r,i){var a,s,l,u,c=e.aoColumns,f=c[n],h=e.aoData;if(r===o)return f.bVisible;if(f.bVisible!==r){if(r){var p=t.inArray(!0,dn(c,"bVisible"),n+1);for(s=0,l=h.length;l>s;s++){u=h[s].nTr;a=h[s].anCells;u&&u.insertBefore(a[n],a[p]||null)}}else t(dn(e.aoData,"anCells",n)).detach();f.bVisible=r;O(e,e.aoHeader);O(e,e.aoFooter);if(i===o||i){d(e);(e.oScroll.sX||e.oScroll.sY)&&me(e)}ze(e,null,"column-visibility",[e,n,r]);je(e)}};Ke("columns()",function(e,n){if(e===o)e="";else if(t.isPlainObject(e)){n=e;e=""}n=An(n);var r=this.iterator("table",function(t){return qn(t,e,n)});r.selector.cols=e;r.selector.opts=n;return r});Ze("columns().header()","column().header()",function(){return this.iterator("column",function(t,e){return t.aoColumns[e].nTh})});Ze("columns().footer()","column().footer()",function(){return this.iterator("column",function(t,e){return t.aoColumns[e].nTf})});Ze("columns().data()","column().data()",function(){return this.iterator("column-rows",function(t,e,n,r,i){for(var o=[],a=0,s=i.length;s>a;a++)o.push(T(t,i[a],e,""));return o})});Ze("columns().cache()","column().cache()",function(t){return this.iterator("column-rows",function(e,n,r,i,o){return pn(e.aoData,o,"search"===t?"_aFilterData":"_aSortData",n)})});Ze("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(t,e,n,r,i){return pn(t.aoData,i,"anCells",e)})});Ze("columns().visible()","column().visible()",function(t,e){return this.iterator("column",function(n,r){return t===o?n.aoColumns[r].bVisible:Un(n,r,t,e)})});Ze("columns().indexes()","column().index()",function(t){return this.iterator("column",function(e,n){return"visible"===t?g(e,n):n})});Ke("columns.adjust()",function(){return this.iterator("table",function(t){d(t)})});Ke("column.index()",function(t,e){if(0!==this.context.length){var n=this.context[0];if("fromVisible"===t||"toData"===t)return p(n,e);if("fromData"===t||"toVisible"===t)return g(n,e)}});Ke("column()",function(t,e){return Nn(this.columns(t,e))});var Bn=function(e,n,r){var i,a,s,l,u,c=e.aoData,f=En(e,r),h=pn(c,f,"anCells"),d=t([].concat.apply([],h)),p=e.aoColumns.length;return Ln(n,function(e){if(null===e||e===o){a=[];for(s=0,l=f.length;l>s;s++){i=f[s];for(u=0;p>u;u++)a.push({row:i,column:u})}return a}return t.isPlainObject(e)?[e]:d.filter(e).map(function(e,n){i=n.parentNode._DT_RowIndex;return{row:i,column:t.inArray(n,c[i].anCells)}}).toArray()})};Ke("cells()",function(e,n,r){if(t.isPlainObject(e))if(typeof e.row!==o){r=n;n=null}else{r=e;e=null}if(t.isPlainObject(n)){r=n;n=null}if(null===n||n===o)return this.iterator("table",function(t){return Bn(t,e,An(r))});var i,a,s,l,u,c=this.columns(n,r),f=this.rows(e,r),h=this.iterator("table",function(t,e){i=[];for(a=0,s=f[e].length;s>a;a++)for(l=0,u=c[e].length;u>l;l++)i.push({row:f[e][a],column:c[e][l]});return i});t.extend(h.selector,{cols:n,rows:e,opts:r});return h});Ze("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(t,e,n){return t.aoData[e].anCells[n]})});Ke("cells().data()",function(){return this.iterator("cell",function(t,e,n){return T(t,e,n)})});Ze("cells().cache()","cell().cache()",function(t){t="search"===t?"_aFilterData":"_aSortData";return this.iterator("cell",function(e,n,r){return e.aoData[n][t][r]})});Ze("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(t,e,n){return{row:e,column:n,columnVisible:g(t,n)}})});Ke(["cells().invalidate()","cell().invalidate()"],function(t){var e=this.selector;this.rows(e.rows,e.opts).invalidate(t);return this});Ke("cell()",function(t,e,n){return Nn(this.cells(t,e,n))});Ke("cell().data()",function(t){var e=this.context,n=this[0];if(t===o)return e.length&&n.length?T(e[0],n[0].row,n[0].column):o;k(e[0],n[0].row,n[0].column,t);E(e[0],n[0].row,"data",n[0].column);return this});Ke("order()",function(e,n){var r=this.context;if(e===o)return 0!==r.length?r[0].aaSorting:o;"number"==typeof e?e=[[e,n]]:t.isArray(e[0])||(e=Array.prototype.slice.call(arguments));return this.iterator("table",function(t){t.aaSorting=e.slice()})});Ke("order.listener()",function(t,e,n){return this.iterator("table",function(r){Ae(r,t,e,n)})});Ke(["columns().order()","column().order()"],function(e){var n=this;return this.iterator("table",function(r,i){var o=[];t.each(n[i],function(t,n){o.push([n,e])});r.aaSorting=o})});Ke("search()",function(e,n,r,i){var a=this.context;return e===o?0!==a.length?a[0].oPreviousSearch.sSearch:o:this.iterator("table",function(o){o.oFeatures.bFilter&&Y(o,t.extend({},o.oPreviousSearch,{sSearch:e+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),1)})});Ze("columns().search()","column().search()",function(e,n,r,i){return this.iterator("column",function(a,s){var l=a.aoPreSearchCols;if(e===o)return l[s].sSearch;if(a.oFeatures.bFilter){t.extend(l[s],{sSearch:e+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i});Y(a,a.oPreviousSearch,1)}})});Ke("state()",function(){return this.context.length?this.context[0].oSavedState:null});Ke("state.clear()",function(){return this.iterator("table",function(t){t.fnStateSaveCallback.call(t.oInstance,t,{})})});Ke("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});Ke("state.save()",function(){return this.iterator("table",function(t){je(t)})});$e.versionCheck=$e.fnVersionCheck=function(t){for(var e,n,r=$e.version.split("."),i=t.split("."),o=0,a=i.length;a>o;o++){e=parseInt(r[o],10)||0;n=parseInt(i[o],10)||0;if(e!==n)return e>n}return!0};$e.isDataTable=$e.fnIsDataTable=function(e){var n=t(e).get(0),r=!1; t.each($e.settings,function(t,e){(e.nTable===n||e.nScrollHead===n||e.nScrollFoot===n)&&(r=!0)});return r};$e.tables=$e.fnTables=function(e){return jQuery.map($e.settings,function(n){return!e||e&&t(n.nTable).is(":visible")?n.nTable:void 0})};$e.camelToHungarian=r;Ke("$()",function(e,n){var r=this.rows(n).nodes(),i=t(r);return t([].concat(i.filter(e).toArray(),i.find(e).toArray()))});t.each(["on","one","off"],function(e,n){Ke(n+"()",function(){var e=Array.prototype.slice.call(arguments);e[0].match(/\.dt\b/)||(e[0]+=".dt");var r=t(this.tables().nodes());r[n].apply(r,e);return this})});Ke("clear()",function(){return this.iterator("table",function(t){A(t)})});Ke("settings()",function(){return new Je(this.context,this.context)});Ke("data()",function(){return this.iterator("table",function(t){return dn(t.aoData,"_aData")}).flatten()});Ke("destroy()",function(e){e=e||!1;return this.iterator("table",function(r){var i,o=r.nTableWrapper.parentNode,a=r.oClasses,s=r.nTable,l=r.nTBody,u=r.nTHead,c=r.nTFoot,f=t(s),h=t(l),d=t(r.nTableWrapper),p=t.map(r.aoData,function(t){return t.nTr});r.bDestroying=!0;ze(r,"aoDestroyCallback","destroy",[r]);e||new Je(r).columns().visible(!0);d.unbind(".DT").find(":not(tbody *)").unbind(".DT");t(n).unbind(".DT-"+r.sInstance);if(s!=u.parentNode){f.children("thead").detach();f.append(u)}if(c&&s!=c.parentNode){f.children("tfoot").detach();f.append(c)}f.detach();d.detach();r.aaSorting=[];r.aaSortingFixed=[];Ne(r);t(p).removeClass(r.asStripeClasses.join(" "));t("th, td",u).removeClass(a.sSortable+" "+a.sSortableAsc+" "+a.sSortableDesc+" "+a.sSortableNone);if(r.bJUI){t("th span."+a.sSortIcon+", td span."+a.sSortIcon,u).detach();t("th, td",u).each(function(){var e=t("div."+a.sSortJUIWrapper,this);t(this).append(e.contents());e.detach()})}!e&&o&&o.insertBefore(s,r.nTableReinsertBefore);h.children().detach();h.append(p);f.css("width",r.sDestroyWidth).removeClass(a.sTable);i=r.asDestroyStripes.length;i&&h.children().each(function(e){t(this).addClass(r.asDestroyStripes[e%i])});var g=t.inArray(r,$e.settings);-1!==g&&$e.settings.splice(g,1)})});$e.version="1.10.2";$e.settings=[];$e.models={};$e.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};$e.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};$e.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};$e.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(t){return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(t){try{return JSON.parse((-1===t.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+t.sInstance+"_"+location.pathname))}catch(e){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(t,e){try{(-1===t.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+t.sInstance+"_"+location.pathname,JSON.stringify(e))}catch(n){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:t.extend({},$e.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};e($e.defaults);$e.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};e($e.defaults.column);$e.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:o,oAjaxData:o,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Be(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Be(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var t=this._iDisplayLength,e=this._iDisplayStart,n=e+t,r=this.aiDisplay.length,i=this.oFeatures,o=i.bPaginate;return i.bServerSide?o===!1||-1===t?e+r:Math.min(e+t,this._iRecordsDisplay):!o||n>r||-1===t?r:n},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};$e.ext=Ye={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:$e.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:$e.version};t.extend(Ye,{afnFiltering:Ye.search,aTypes:Ye.type.detect,ofnSearch:Ye.type.search,oSort:Ye.type.order,afnSortData:Ye.order,aoFeatures:Ye.feature,oApi:Ye.internal,oStdClasses:Ye.classes,oPagination:Ye.pager});t.extend($e.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});(function(){var e="";e="";var n=e+"ui-state-default",r=e+"css_right ui-icon ui-icon-",i=e+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";t.extend($e.ext.oJUIClasses,$e.ext.classes,{sPageButton:"fg-button ui-button "+n,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:n+" sorting_asc",sSortDesc:n+" sorting_desc",sSortable:n+" sorting",sSortableAsc:n+" sorting_asc_disabled",sSortableDesc:n+" sorting_desc_disabled",sSortableNone:n+" sorting_disabled",sSortJUIAsc:r+"triangle-1-n",sSortJUIDesc:r+"triangle-1-s",sSortJUI:r+"carat-2-n-s",sSortJUIAscAllowed:r+"carat-1-n",sSortJUIDescAllowed:r+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+n,sScrollFoot:"dataTables_scrollFoot "+n,sHeaderTH:n,sFooterTH:n,sJUIHeader:i+" ui-corner-tl ui-corner-tr",sJUIFooter:i+" ui-corner-bl ui-corner-br"})})();var Vn=$e.ext.pager;t.extend(Vn,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(t,e){return["previous",Ve(t,e),"next"]},full_numbers:function(t,e){return["first","previous",Ve(t,e),"next","last"]},_numbers:Ve,numbers_length:7});t.extend(!0,$e.ext.renderer,{pageButton:{_:function(e,n,r,o,a,s){var l,u,c=e.oClasses,f=e.oLanguage.oPaginate,h=0,d=function(n,i){var o,p,g,m,v=function(t){he(e,t.data.action,!0)};for(o=0,p=i.length;p>o;o++){m=i[o];if(t.isArray(m)){var y=t("<"+(m.DT_el||"div")+"/>").appendTo(n);d(y,m)}else{l="";u="";switch(m){case"ellipsis":n.append("<span>&hellip;</span>");break;case"first":l=f.sFirst;u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"previous":l=f.sPrevious;u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"next":l=f.sNext;u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;case"last":l=f.sLast;u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;default:l=m+1;u=a===m?c.sPageButtonActive:""}if(l){g=t("<a>",{"class":c.sPageButton+" "+u,"aria-controls":e.sTableId,"data-dt-idx":h,tabindex:e.iTabIndex,id:0===r&&"string"==typeof m?e.sTableId+"_"+m:null}).html(l).appendTo(n);Re(g,{action:m},v);h++}}}};try{var p=t(i.activeElement).data("dt-idx");d(t(n).empty(),o);null!==p&&t(n).find("[data-dt-idx="+p+"]").focus()}catch(g){}}}});var Xn=function(t,e,n,r){if(!t||"-"===t)return-1/0;e&&(t=un(t,e));if(t.replace){n&&(t=t.replace(n,""));r&&(t=t.replace(r,""))}return 1*t};t.extend(Ye.type.order,{"date-pre":function(t){return Date.parse(t)||0},"html-pre":function(t){return sn(t)?"":t.replace?t.replace(/<.*?>/g,"").toLowerCase():t+""},"string-pre":function(t){return sn(t)?"":"string"==typeof t?t.toLowerCase():t.toString?t.toString():""},"string-asc":function(t,e){return e>t?-1:t>e?1:0},"string-desc":function(t,e){return e>t?1:t>e?-1:0}});Xe("");t.extend($e.ext.type.detect,[function(t,e){var n=e.oLanguage.sDecimal;return cn(t,n)?"num"+n:null},function(t){if(t&&(!nn.test(t)||!rn.test(t)))return null;var e=Date.parse(t);return null!==e&&!isNaN(e)||sn(t)?"date":null},function(t,e){var n=e.oLanguage.sDecimal;return cn(t,n,!0)?"num-fmt"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return hn(t,n)?"html-num"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return hn(t,n,!0)?"html-num-fmt"+n:null},function(t){return sn(t)||"string"==typeof t&&-1!==t.indexOf("<")?"html":null}]);t.extend($e.ext.type.search,{html:function(t){return sn(t)?t:"string"==typeof t?t.replace(tn," ").replace(en,""):""},string:function(t){return sn(t)?t:"string"==typeof t?t.replace(tn," "):t}});t.extend(!0,$e.ext.renderer,{header:{_:function(e,n,r,i){t(e.nTable).on("order.dt.DT",function(t,o,a,s){if(e===o){var l=r.idx;n.removeClass(r.sSortingClass+" "+i.sSortAsc+" "+i.sSortDesc).addClass("asc"==s[l]?i.sSortAsc:"desc"==s[l]?i.sSortDesc:r.sSortingClass)}})},jqueryui:function(e,n,r,i){var o=r.idx;t("<div/>").addClass(i.sSortJUIWrapper).append(n.contents()).append(t("<span/>").addClass(i.sSortIcon+" "+r.sSortingClassJUI)).appendTo(n);t(e.nTable).on("order.dt.DT",function(t,a,s,l){if(e===a){n.removeClass(i.sSortAsc+" "+i.sSortDesc).addClass("asc"==l[o]?i.sSortAsc:"desc"==l[o]?i.sSortDesc:r.sSortingClass);n.find("span."+i.sSortIcon).removeClass(i.sSortJUIAsc+" "+i.sSortJUIDesc+" "+i.sSortJUI+" "+i.sSortJUIAscAllowed+" "+i.sSortJUIDescAllowed).addClass("asc"==l[o]?i.sSortJUIAsc:"desc"==l[o]?i.sSortJUIDesc:r.sSortingClassJUI)}})}}});$e.render={number:function(t,e,n,r){return{display:function(i){var o=0>i?"-":"";i=Math.abs(parseFloat(i));var a=parseInt(i,10),s=n?e+(i-a).toFixed(n).substring(2):"";return o+(r||"")+a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,t)+s}}}};t.extend($e.ext.internal,{_fnExternApiFunc:Ge,_fnBuildAjax:U,_fnAjaxUpdate:B,_fnAjaxParameters:V,_fnAjaxUpdateDraw:X,_fnAjaxDataSrc:G,_fnAddColumn:f,_fnColumnOptions:h,_fnAdjustColumnSizing:d,_fnVisibleToColumnIndex:p,_fnColumnIndexToVisible:g,_fnVisbleColumns:m,_fnGetColumns:v,_fnColumnTypes:y,_fnApplyColumnDefs:b,_fnHungarianMap:e,_fnCamelToHungarian:r,_fnLanguageCompat:a,_fnBrowserDetect:u,_fnAddData:x,_fnAddTr:w,_fnNodeToDataIndex:C,_fnNodeToColumnIndex:S,_fnGetCellData:T,_fnSetCellData:k,_fnSplitObjNotation:_,_fnGetObjectDataFn:M,_fnSetObjectDataFn:D,_fnGetDataMaster:L,_fnClearTable:A,_fnDeleteIndex:N,_fnInvalidateRow:E,_fnGetRowElements:j,_fnCreateTr:I,_fnBuildHead:H,_fnDrawHead:O,_fnDraw:F,_fnReDraw:R,_fnAddOptionsHtml:W,_fnDetectHeader:z,_fnGetUniqueThs:q,_fnFeatureHtmlFilter:$,_fnFilterComplete:Y,_fnFilterCustom:J,_fnFilterColumn:K,_fnFilter:Z,_fnFilterCreateSearch:Q,_fnEscapeRegex:te,_fnFilterData:ee,_fnFeatureHtmlInfo:ie,_fnUpdateInfo:oe,_fnInfoMacros:ae,_fnInitialise:se,_fnInitComplete:le,_fnLengthChange:ue,_fnFeatureHtmlLength:ce,_fnFeatureHtmlPaginate:fe,_fnPageChange:he,_fnFeatureHtmlProcessing:de,_fnProcessingDisplay:pe,_fnFeatureHtmlTable:ge,_fnScrollDraw:me,_fnApplyToChildren:ve,_fnCalculateColumnWidths:ye,_fnThrottle:be,_fnConvertToWidth:xe,_fnScrollingWidthAdjust:we,_fnGetWidestNode:Ce,_fnGetMaxLenString:Se,_fnStringToCss:Te,_fnScrollBarWidth:ke,_fnSortFlatten:_e,_fnSort:Me,_fnSortAria:De,_fnSortListener:Le,_fnSortAttachListener:Ae,_fnSortingClasses:Ne,_fnSortData:Ee,_fnSaveState:je,_fnLoadState:Ie,_fnSettingsFromNode:Pe,_fnLog:He,_fnMap:Oe,_fnBindAction:Re,_fnCallbackReg:We,_fnCallbackFire:ze,_fnLengthOverflow:qe,_fnRenderer:Ue,_fnDataSource:Be,_fnRowAttributes:P,_fnCalculateEnd:function(){}});t.fn.dataTable=$e;t.fn.dataTableSettings=$e.settings;t.fn.dataTableExt=$e.ext;t.fn.DataTable=function(e){return t(this).dataTable(e).api()};t.each($e,function(e,n){t.fn.DataTable[e]=n});return t.fn.dataTable})})(window,document)},{jquery:18}],3:[function(){RegExp.escape=function(t){return t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};(function(t){"use strict";t.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(t){var e=/\./;if(isNaN(t))return t;if(e.test(t))return parseFloat(t);var n=parseInt(t);return isNaN(n)?null:n}},parsers:{parse:function(t,e){function n(){l=0;u="";if(e.start&&e.state.rowNum<e.start){s=[];e.state.rowNum++;e.state.colNum=1}else{if(void 0===e.onParseEntry)a.push(s);else{var t=e.onParseEntry(s,e.state);t!==!1&&a.push(t)}s=[];e.end&&e.state.rowNum>=e.end&&(c=!0);e.state.rowNum++;e.state.colNum=1}}function r(){if(void 0===e.onParseValue)s.push(u);else{var t=e.onParseValue(u,e.state);t!==!1&&s.push(t)}u="";l=0;e.state.colNum++}var i=e.separator,o=e.delimiter;e.state.rowNum||(e.state.rowNum=1);e.state.colNum||(e.state.colNum=1);var a=[],s=[],l=0,u="",c=!1,f=RegExp.escape(i),h=RegExp.escape(o),d=/(D|S|\n|\r|[^DS\r\n]+)/,p=d.source;p=p.replace(/S/g,f);p=p.replace(/D/g,h);d=RegExp(p,"gm");t.replace(d,function(t){if(!c)switch(l){case 0:if(t===i){u+="";r();break}if(t===o){l=1;break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;u+=t;l=3;break;case 1:if(t===o){l=2;break}u+=t;l=1;break;case 2:if(t===o){u+=t;l=1;break}if(t===i){r();break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;throw new Error("CSVDataError: Illegal State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");case 3:if(t===i){r();break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;if(t===o)throw new Error("CSVDataError: Illegal Quote [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]")}});if(0!==s.length){r();n()}return a},splitLines:function(t,e){function n(){a=0;if(e.start&&e.state.rowNum<e.start){s="";e.state.rowNum++}else{if(void 0===e.onParseEntry)o.push(s);else{var t=e.onParseEntry(s,e.state);t!==!1&&o.push(t)}s="";e.end&&e.state.rowNum>=e.end&&(l=!0);e.state.rowNum++}}var r=e.separator,i=e.delimiter;e.state.rowNum||(e.state.rowNum=1);var o=[],a=0,s="",l=!1,u=RegExp.escape(r),c=RegExp.escape(i),f=/(D|S|\n|\r|[^DS\r\n]+)/,h=f.source;h=h.replace(/S/g,u);h=h.replace(/D/g,c);f=RegExp(h,"gm");t.replace(f,function(t){if(!l)switch(a){case 0:if(t===r){s+=t;a=0;break}if(t===i){s+=t;a=1;break}if("\n"===t){n();break}if(/^\r$/.test(t))break;s+=t;a=3;break;case 1:if(t===i){s+=t;a=2;break}s+=t;a=1;break;case 2:var o=s.substr(s.length-1);if(t===i&&o===i){s+=t;a=1;break}if(t===r){s+=t;a=0;break}if("\n"===t){n();break}if("\r"===t)break;throw new Error("CSVDataError: Illegal state [Row:"+e.state.rowNum+"]");case 3:if(t===r){s+=t;a=0;break}if("\n"===t){n();break}if("\r"===t)break;if(t===i)throw new Error("CSVDataError: Illegal quote [Row:"+e.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+e.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+e.state.rowNum+"]")}});""!==s&&n();return o},parseEntry:function(t,e){function n(){if(void 0===e.onParseValue)o.push(s);else{var t=e.onParseValue(s,e.state);t!==!1&&o.push(t)}s="";a=0;e.state.colNum++}var r=e.separator,i=e.delimiter;e.state.rowNum||(e.state.rowNum=1);e.state.colNum||(e.state.colNum=1);var o=[],a=0,s="";if(!e.match){var l=RegExp.escape(r),u=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,f=c.source;f=f.replace(/S/g,l);f=f.replace(/D/g,u);e.match=RegExp(f,"gm")}t.replace(e.match,function(t){switch(a){case 0:if(t===r){s+="";n();break}if(t===i){a=1;break}if("\n"===t||"\r"===t)break;s+=t;a=3;break;case 1:if(t===i){a=2;break}s+=t;a=1;break;case 2:if(t===i){s+=t;a=1;break}if(t===r){n();break}if("\n"===t||"\r"===t)break;throw new Error("CSVDataError: Illegal State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");case 3:if(t===r){n();break}if("\n"===t||"\r"===t)break;if(t===i)throw new Error("CSVDataError: Illegal Quote [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]")}});n();return o}},toArray:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},a=t.csv.parsers.parseEntry(e,n);if(!i.callback)return a;i.callback("",a);return void 0},toArrays:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};o=t.csv.parsers.parse(e,n);if(!i.callback)return o;i.callback("",o);return void 0},toObjects:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;i.headers="headers"in n?n.headers:t.csv.defaults.headers;n.start="start"in n?n.start:1;i.headers&&n.start++;n.end&&i.headers&&n.end++;var o=[],a=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},s={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=t.csv.parsers.splitLines(e,s),u=t.csv.toArray(l[0],n),o=t.csv.parsers.splitLines(e,n);n.state.colNum=1;n.state.rowNum=u?2:1;for(var c=0,f=o.length;f>c;c++){var h=t.csv.toArray(o[c],n),d={};for(var p in u)d[u[p]]=h[p];a.push(d);n.state.rowNum++}if(!i.callback)return a;i.callback("",a);return void 0},fromArrays:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.escaper="escaper"in n?n.escaper:t.csv.defaults.escaper;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var a=[];for(i in e)a.push(e[i]);if(!o.callback)return a;o.callback("",a);return void 0},fromObjects2CSV:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var a=[];for(i in e)a.push(arrays[i]);if(!o.callback)return a;o.callback("",a);return void 0}};t.csvEntry2Array=t.csv.toArray;t.csv2Array=t.csv.toArrays;t.csv2Dictionary=t.csv.toObjects})(jQuery)},{}],4:[function(t,e){function n(){this._events=this._events||{};this._maxListeners=this._maxListeners||void 0}function r(t){return"function"==typeof t}function i(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}e.exports=n;n.EventEmitter=n;n.prototype._events=void 0;n.prototype._maxListeners=void 0;n.defaultMaxListeners=10;n.prototype.setMaxListeners=function(t){if(!i(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");this._maxListeners=t;return this};n.prototype.emit=function(t){var e,n,i,s,l,u;this._events||(this._events={});if("error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){e=arguments[1];if(e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}n=this._events[t];if(a(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=arguments.length;s=new Array(i-1);for(l=1;i>l;l++)s[l-1]=arguments[l];n.apply(this,s)}else if(o(n)){i=arguments.length;s=new Array(i-1);for(l=1;i>l;l++)s[l-1]=arguments[l];u=n.slice();i=u.length;for(l=0;i>l;l++)u[l].apply(this,s)}return!0};n.prototype.addListener=function(t,e){var i;if(!r(e))throw TypeError("listener must be a function");this._events||(this._events={});this._events.newListener&&this.emit("newListener",t,r(e.listener)?e.listener:e);this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e;if(o(this._events[t])&&!this._events[t].warned){var i;i=a(this._maxListeners)?n.defaultMaxListeners:this._maxListeners;if(i&&i>0&&this._events[t].length>i){this._events[t].warned=!0;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length);"function"==typeof console.trace&&console.trace()}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(t,e){function n(){this.removeListener(t,n);if(!i){i=!0;e.apply(this,arguments)}}if(!r(e))throw TypeError("listener must be a function");var i=!1;n.listener=e;this.on(t,n);return this};n.prototype.removeListener=function(t,e){var n,i,a,s;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;n=this._events[t];a=n.length;i=-1;if(n===e||r(n.listener)&&n.listener===e){delete this._events[t];this._events.removeListener&&this.emit("removeListener",t,e)}else if(o(n)){for(s=a;s-->0;)if(n[s]===e||n[s].listener&&n[s].listener===e){i=s;break}if(0>i)return this;if(1===n.length){n.length=0;delete this._events[t]}else n.splice(i,1);this._events.removeListener&&this.emit("removeListener",t,e)}return this};n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener){0===arguments.length?this._events={}:this._events[t]&&delete this._events[t];return this}if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);this.removeAllListeners("removeListener");this._events={};return this}n=this._events[t];if(r(n))this.removeListener(t,n);else for(;n.length;)this.removeListener(t,n[n.length-1]);delete this._events[t];return this};n.prototype.listeners=function(t){var e;e=this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[];return e};n.listenerCount=function(t,e){var n;n=t._events&&t._events[e]?r(t._events[e])?1:t._events[e].length:0;return n}},{}],5:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){function e(t,e,r,i){var o=t.getLineHandle(e.line),l=e.ch-1,u=l>=0&&s[o.text.charAt(l)]||s[o.text.charAt(++l)];if(!u)return null;var c=">"==u.charAt(1)?1:-1;if(r&&c>0!=(l==e.ch))return null;var f=t.getTokenTypeAt(a(e.line,l+1)),h=n(t,a(e.line,l+(c>0?1:0)),c,f||null,i);return null==h?null:{from:a(e.line,l),to:h&&h.pos,match:h&&h.ch==u.charAt(0),forward:c>0}}function n(t,e,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],c=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,f=n>0?Math.min(e.line+l,t.lastLine()+1):Math.max(t.firstLine()-1,e.line-l),h=e.line;h!=f;h+=n){var d=t.getLine(h);if(d){var p=n>0?0:d.length-1,g=n>0?d.length:-1;if(!(d.length>o)){h==e.line&&(p=e.ch-(0>n?1:0));for(;p!=g;p+=n){var m=d.charAt(p);if(c.test(m)&&(void 0===r||t.getTokenTypeAt(a(h,p+1))==r)){var v=s[m];if(">"==v.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:a(h,p),ch:m};u.pop()}}}}}}return h-n==(n>0?t.lastLine():t.firstLine())?!1:null}function r(t,n,r){for(var i=t.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=t.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&e(t,l[u].head,!1,r);if(c&&t.getLine(c.from.line).length<=i){var f=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";s.push(t.markText(c.from,a(c.from.line,c.from.ch+1),{className:f}));c.to&&t.getLine(c.to.line).length<=i&&s.push(t.markText(c.to,a(c.to.line,c.to.ch+1),{className:f}))}}if(s.length){o&&t.state.focused&&t.display.input.focus();var h=function(){t.operation(function(){for(var t=0;t<s.length;t++)s[t].clear()})};if(!n)return h;setTimeout(h,800)}}function i(t){t.operation(function(){if(l){l();l=null}l=r(t,!1,t.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),a=t.Pos,s={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;t.defineOption("matchBrackets",!1,function(e,n,r){r&&r!=t.Init&&e.off("cursorActivity",i);if(n){e.state.matchBrackets="object"==typeof n?n:{};e.on("cursorActivity",i)}});t.defineExtension("matchBrackets",function(){r(this,!0)});t.defineExtension("findMatchingBracket",function(t,n,r){return e(this,t,n,r)});t.defineExtension("scanForBracket",function(t,e,r,i){return n(this,t,e,r,i)})})},{"../../lib/codemirror":10}],6:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.registerHelper("fold","brace",function(e,n){function r(r){for(var i=n.ch,l=0;;){var u=0>=i?-1:s.lastIndexOf(r,i-1);if(-1!=u){if(1==l&&u<n.ch)break;o=e.getTokenTypeAt(t.Pos(a,u+1));if(!/^(comment|string)/.test(o))return u+1;i=u-1}else{if(1==l)break;l=1;i=s.length}}}var i,o,a=n.line,s=e.getLine(a),l="{",u="}",i=r("{");if(null==i){l="[",u="]";i=r("[")}if(null!=i){var c,f,h=1,d=e.lastLine();t:for(var p=a;d>=p;++p)for(var g=e.getLine(p),m=p==a?i:0;;){var v=g.indexOf(l,m),y=g.indexOf(u,m);0>v&&(v=g.length);0>y&&(y=g.length);m=Math.min(v,y);if(m==g.length)break;if(e.getTokenTypeAt(t.Pos(p,m+1))==o)if(m==v)++h;else if(!--h){c=p;f=m;break t}++m}if(null!=c&&(a!=c||f!=i))return{from:t.Pos(a,i),to:t.Pos(c,f)}}});t.registerHelper("fold","import",function(e,n){function r(n){if(n<e.firstLine()||n>e.lastLine())return null;var r=e.getTokenAt(t.Pos(n,1));/\S/.test(r.string)||(r=e.getTokenAt(t.Pos(n,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(e.lastLine(),n+10);o>=i;++i){var a=e.getLine(i),s=a.indexOf(";");if(-1!=s)return{startCh:r.end,end:t.Pos(i,s)}}}var i,n=n.line,o=r(n);if(!o||r(n-1)||(i=r(n-2))&&i.end.line==n-1)return null;for(var a=o.end;;){var s=r(a.line+1);if(null==s)break;a=s.end}return{from:e.clipPos(t.Pos(n,o.startCh+1)),to:a}});t.registerHelper("fold","include",function(e,n){function r(n){if(n<e.firstLine()||n>e.lastLine())return null;var r=e.getTokenAt(t.Pos(n,1));/\S/.test(r.string)||(r=e.getTokenAt(t.Pos(n,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var n=n.line,i=r(n);if(null==i||null!=r(n-1))return null;for(var o=n;;){var a=r(o+1);if(null==a)break;++o}return{from:t.Pos(n,i+1),to:e.clipPos(t.Pos(o))}})})},{"../../lib/codemirror":10}],7:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";function e(e,i,o,a){function s(t){var n=l(e,i);if(!n||n.to.line-n.from.line<u)return null;for(var r=e.findMarksAt(n.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==a){if(!t)return null;n.cleared=!0;r[o].clear()}return n}if(o&&o.call){var l=o;o=null}else var l=r(e,o,"rangeFinder");"number"==typeof i&&(i=t.Pos(i,0));var u=r(e,o,"minFoldSize"),c=s(!0);if(r(e,o,"scanUp"))for(;!c&&i.line>e.firstLine();){i=t.Pos(i.line-1,0);c=s(!1)}if(c&&!c.cleared&&"unfold"!==a){var f=n(e,o);t.on(f,"mousedown",function(e){h.clear();t.e_preventDefault(e)});var h=e.markText(c.from,c.to,{replacedWith:f,clearOnEnter:!0,__isFold:!0});h.on("clear",function(n,r){t.signal(e,"unfold",e,n,r)});t.signal(e,"fold",e,c.from,c.to)}}function n(t,e){var n=r(t,e,"widget");if("string"==typeof n){var i=document.createTextNode(n);n=document.createElement("span");n.appendChild(i);n.className="CodeMirror-foldmarker"}return n}function r(t,e,n){if(e&&void 0!==e[n])return e[n];var r=t.options.foldOptions;return r&&void 0!==r[n]?r[n]:i[n]}t.newFoldFunction=function(t,n){return function(r,i){e(r,i,{rangeFinder:t,widget:n})}};t.defineExtension("foldCode",function(t,n,r){e(this,t,n,r)});t.defineExtension("isFolded",function(t){for(var e=this.findMarksAt(t),n=0;n<e.length;++n)if(e[n].__isFold)return!0});t.commands.toggleFold=function(t){t.foldCode(t.getCursor())};t.commands.fold=function(t){t.foldCode(t.getCursor(),null,"fold")};t.commands.unfold=function(t){t.foldCode(t.getCursor(),null,"unfold")};t.commands.foldAll=function(e){e.operation(function(){for(var n=e.firstLine(),r=e.lastLine();r>=n;n++)e.foldCode(t.Pos(n,0),null,"fold") })};t.commands.unfoldAll=function(e){e.operation(function(){for(var n=e.firstLine(),r=e.lastLine();r>=n;n++)e.foldCode(t.Pos(n,0),null,"unfold")})};t.registerHelper("fold","combine",function(){var t=Array.prototype.slice.call(arguments,0);return function(e,n){for(var r=0;r<t.length;++r){var i=t[r](e,n);if(i)return i}}});t.registerHelper("fold","auto",function(t,e){for(var n=t.getHelpers(e,"fold"),r=0;r<n.length;r++){var i=n[r](t,e);if(i)return i}});var i={rangeFinder:t.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};t.defineOption("foldOptions",null)})},{"../../lib/codemirror":10}],8:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror"),e("./foldcode")):"function"==typeof t&&t.amd?t(["../../lib/codemirror","./foldcode"],i):i(CodeMirror)})(function(t){"use strict";function e(t){this.options=t;this.from=this.to=0}function n(t){t===!0&&(t={});null==t.gutter&&(t.gutter="CodeMirror-foldgutter");null==t.indicatorOpen&&(t.indicatorOpen="CodeMirror-foldgutter-open");null==t.indicatorFolded&&(t.indicatorFolded="CodeMirror-foldgutter-folded");return t}function r(t,e){for(var n=t.findMarksAt(f(e)),r=0;r<n.length;++r)if(n[r].__isFold&&n[r].find().from.line==e)return!0}function i(t){if("string"==typeof t){var e=document.createElement("div");e.className=t+" CodeMirror-guttermarker-subtle";return e}return t.cloneNode(!0)}function o(e,n,o){var a=e.state.foldGutter.options,s=n;e.eachLine(n,o,function(n){var o=null;if(r(e,s))o=i(a.indicatorFolded);else{var l=f(s,0),u=a.rangeFinder||t.fold.auto,c=u&&u(e,l);c&&c.from.line+1<c.to.line&&(o=i(a.indicatorOpen))}e.setGutterMarker(n,a.gutter,o);++s})}function a(t){var e=t.getViewport(),n=t.state.foldGutter;if(n){t.operation(function(){o(t,e.from,e.to)});n.from=e.from;n.to=e.to}}function s(t,e,n){var r=t.state.foldGutter.options;n==r.gutter&&t.foldCode(f(e,0),r.rangeFinder)}function l(t){var e=t.state.foldGutter,n=t.state.foldGutter.options;e.from=e.to=0;clearTimeout(e.changeUpdate);e.changeUpdate=setTimeout(function(){a(t)},n.foldOnChangeTimeSpan||600)}function u(t){var e=t.state.foldGutter,n=t.state.foldGutter.options;clearTimeout(e.changeUpdate);e.changeUpdate=setTimeout(function(){var n=t.getViewport();e.from==e.to||n.from-e.to>20||e.from-n.to>20?a(t):t.operation(function(){if(n.from<e.from){o(t,n.from,e.from);e.from=n.from}if(n.to>e.to){o(t,e.to,n.to);e.to=n.to}})},n.updateViewportTimeSpan||400)}function c(t,e){var n=t.state.foldGutter,r=e.line;r>=n.from&&r<n.to&&o(t,r,r+1)}t.defineOption("foldGutter",!1,function(r,i,o){if(o&&o!=t.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",s);r.off("change",l);r.off("viewportChange",u);r.off("fold",c);r.off("unfold",c);r.off("swapDoc",a)}if(i){r.state.foldGutter=new e(n(i));a(r);r.on("gutterClick",s);r.on("change",l);r.on("viewportChange",u);r.on("fold",c);r.on("unfold",c);r.on("swapDoc",a)}});var f=t.Pos})},{"../../lib/codemirror":10,"./foldcode":7}],9:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";function e(t,e){return t.line-e.line||t.ch-e.ch}function n(t,e,n,r){this.line=e;this.ch=n;this.cm=t;this.text=t.getLine(e);this.min=r?r.from:t.firstLine();this.max=r?r.to-1:t.lastLine()}function r(t,e){var n=t.cm.getTokenTypeAt(h(t.line,e));return n&&/\btag\b/.test(n)}function i(t){if(!(t.line>=t.max)){t.ch=0;t.text=t.cm.getLine(++t.line);return!0}}function o(t){if(!(t.line<=t.min)){t.text=t.cm.getLine(--t.line);t.ch=t.text.length;return!0}}function a(t){for(;;){var e=t.text.indexOf(">",t.ch);if(-1==e){if(i(t))continue;return}if(r(t,e+1)){var n=t.text.lastIndexOf("/",e),o=n>-1&&!/\S/.test(t.text.slice(n+1,e));t.ch=e+1;return o?"selfClose":"regular"}t.ch=e+1}}function s(t){for(;;){var e=t.ch?t.text.lastIndexOf("<",t.ch-1):-1;if(-1==e){if(o(t))continue;return}if(r(t,e+1)){g.lastIndex=e;t.ch=e;var n=g.exec(t.text);if(n&&n.index==e)return n}else t.ch=e}}function l(t){for(;;){g.lastIndex=t.ch;var e=g.exec(t.text);if(!e){if(i(t))continue;return}if(r(t,e.index+1)){t.ch=e.index+e[0].length;return e}t.ch=e.index+1}}function u(t){for(;;){var e=t.ch?t.text.lastIndexOf(">",t.ch-1):-1;if(-1==e){if(o(t))continue;return}if(r(t,e+1)){var n=t.text.lastIndexOf("/",e),i=n>-1&&!/\S/.test(t.text.slice(n+1,e));t.ch=e+1;return i?"selfClose":"regular"}t.ch=e}}function c(t,e){for(var n=[];;){var r,i=l(t),o=t.line,s=t.ch-(i?i[0].length:0);if(!i||!(r=a(t)))return;if("selfClose"!=r)if(i[1]){for(var u=n.length-1;u>=0;--u)if(n[u]==i[2]){n.length=u;break}if(0>u&&(!e||e==i[2]))return{tag:i[2],from:h(o,s),to:h(t.line,t.ch)}}else n.push(i[2])}}function f(t,e){for(var n=[];;){var r=u(t);if(!r)return;if("selfClose"!=r){var i=t.line,o=t.ch,a=s(t);if(!a)return;if(a[1])n.push(a[2]);else{for(var l=n.length-1;l>=0;--l)if(n[l]==a[2]){n.length=l;break}if(0>l&&(!e||e==a[2]))return{tag:a[2],from:h(t.line,t.ch),to:h(i,o)}}}else s(t)}}var h=t.Pos,d="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",p=d+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",g=new RegExp("<(/?)(["+d+"]["+p+"]*)","g");t.registerHelper("fold","xml",function(t,e){for(var r=new n(t,e.line,0);;){var i,o=l(r);if(!o||r.line!=e.line||!(i=a(r)))return;if(!o[1]&&"selfClose"!=i){var e=h(r.line,r.ch),s=c(r,o[2]);return s&&{from:e,to:s.from}}}});t.findMatchingTag=function(t,r,i){var o=new n(t,r.line,r.ch,i);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=a(o),u=l&&h(o.line,o.ch),d=l&&s(o);if(l&&d&&!(e(o,r)>0)){var p={from:h(o.line,o.ch),to:u,tag:d[2]};if("selfClose"==l)return{open:p,close:null,at:"open"};if(d[1])return{open:f(o,d[2]),close:p,at:"close"};o=new n(t,u.line,u.ch,i);return{open:p,close:c(o,d[2]),at:"open"}}}};t.findEnclosingTag=function(t,e,r){for(var i=new n(t,e.line,e.ch,r);;){var o=f(i);if(!o)break;var a=new n(t,e.line,e.ch,r),s=c(a,o.tag);if(s)return{open:o,close:s}}};t.scanForClosingTag=function(t,e,r,i){var o=new n(t,e.line,e.ch,i?{from:0,to:i}:null);return c(o,r)}})},{"../../lib/codemirror":10}],10:[function(e,n,r){(function(e){if("object"==typeof r&&"object"==typeof n)n.exports=e();else{if("function"==typeof t&&t.amd)return t([],e);this.CodeMirror=e()}})(function(){"use strict";function t(n,r){if(!(this instanceof t))return new t(n,r);this.options=r=r?yo(r):{};yo(ja,r,!1);d(r);var i=r.value;"string"==typeof i&&(i=new rs(i,r.mode));this.doc=i;var o=this.display=new e(n,i);o.wrapper.CodeMirror=this;u(this);s(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!ca&&kn(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new co,keySeq:null};Qo&&11>ta&&setTimeout(bo(Tn,this,!0),20);Dn(this);No();Ze(this);this.curOp.forceUpdate=!0;Ni(this,i);r.autofocus&&!ca||Mo()==o.input?setTimeout(bo(Zn,this),20):Qn(this);for(var a in Ia)Ia.hasOwnProperty(a)&&Ia[a](this,r[a],Pa);b(this);for(var l=0;l<Ra.length;++l)Ra[l](this);tn(this)}function e(t,e){var n=this,r=n.input=So("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ea?r.style.width="1000px":r.setAttribute("wrap","off");ua&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");n.inputDiv=So("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");n.scrollbarH=So("div",[So("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.scrollbarV=So("div",[So("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar");n.scrollbarFiller=So("div",null,"CodeMirror-scrollbar-filler");n.gutterFiller=So("div",null,"CodeMirror-gutter-filler");n.lineDiv=So("div",null,"CodeMirror-code");n.selectionDiv=So("div",null,null,"position: relative; z-index: 1");n.cursorDiv=So("div",null,"CodeMirror-cursors");n.measure=So("div",null,"CodeMirror-measure");n.lineMeasure=So("div",null,"CodeMirror-measure");n.lineSpace=So("div",[n.measure,n.lineMeasure,n.selectionDiv,n.cursorDiv,n.lineDiv],null,"position: relative; outline: none");n.mover=So("div",[So("div",[n.lineSpace],"CodeMirror-lines")],null,"position: relative");n.sizer=So("div",[n.mover],"CodeMirror-sizer");n.heightForcer=So("div",null,null,"position: absolute; height: "+ds+"px; width: 1px;");n.gutters=So("div",null,"CodeMirror-gutters");n.lineGutter=null;n.scroller=So("div",[n.sizer,n.heightForcer,n.gutters],"CodeMirror-scroll");n.scroller.setAttribute("tabIndex","-1");n.wrapper=So("div",[n.inputDiv,n.scrollbarH,n.scrollbarV,n.scrollbarFiller,n.gutterFiller,n.scroller],"CodeMirror");if(Qo&&8>ta){n.gutters.style.zIndex=-1;n.scroller.style.paddingRight=0}ua&&(r.style.width="0px");ea||(n.scroller.draggable=!0);if(aa){n.inputDiv.style.height="1px";n.inputDiv.style.position="absolute"}Qo&&8>ta&&(n.scrollbarH.style.minHeight=n.scrollbarV.style.minWidth="18px");t&&(t.appendChild?t.appendChild(n.wrapper):t(n.wrapper));n.viewFrom=n.viewTo=e.first;n.view=[];n.externalMeasured=null;n.viewOffset=0;n.lastWrapHeight=n.lastWrapWidth=0;n.updateLineNumbers=null;n.lineNumWidth=n.lineNumInnerWidth=n.lineNumChars=null;n.prevInput="";n.alignWidgets=!1;n.pollingFast=!1;n.poll=new co;n.cachedCharWidth=n.cachedTextHeight=n.cachedPaddingH=null;n.inaccurateSelection=!1;n.maxLine=null;n.maxLineLength=0;n.maxLineChanged=!1;n.wheelDX=n.wheelDY=n.wheelStartX=n.wheelStartY=null;n.shift=!1;n.selForContextMenu=null}function n(e){e.doc.mode=t.getMode(e.options,e.doc.modeOption);r(e)}function r(t){t.doc.iter(function(t){t.stateAfter&&(t.stateAfter=null);t.styles&&(t.styles=null)});t.doc.frontier=t.doc.first;we(t,100);t.state.modeGen++;t.curOp&&pn(t)}function i(t){if(t.options.lineWrapping){Ls(t.display.wrapper,"CodeMirror-wrap");t.display.sizer.style.minWidth=""}else{Ds(t.display.wrapper,"CodeMirror-wrap");h(t)}a(t);pn(t);Re(t);setTimeout(function(){m(t)},100)}function o(t){var e=Je(t.display),n=t.options.lineWrapping,r=n&&Math.max(5,t.display.scroller.clientWidth/Ke(t.display)-3);return function(i){if(ri(t.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a<i.widgets.length;a++)i.widgets[a].height&&(o+=i.widgets[a].height);return n?o+(Math.ceil(i.text.length/r)||1)*e:o+e}}function a(t){var e=t.doc,n=o(t);e.iter(function(t){var e=n(t);e!=t.height&&Pi(t,e)})}function s(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-");Re(t)}function l(t){u(t);pn(t);setTimeout(function(){y(t)},20)}function u(t){var e=t.display.gutters,n=t.options.gutters;To(e);for(var r=0;r<n.length;++r){var i=n[r],o=e.appendChild(So("div",null,"CodeMirror-gutter "+i));if("CodeMirror-linenumbers"==i){t.display.lineGutter=o;o.style.width=(t.display.lineNumWidth||1)+"px"}}e.style.display=r?"":"none";c(t)}function c(t){var e=t.display.gutters.offsetWidth;t.display.sizer.style.marginLeft=e+"px";t.display.scrollbarH.style.left=t.options.fixedGutter?e+"px":0}function f(t){if(0==t.height)return 0;for(var e,n=t.text.length,r=t;e=Jr(r);){var i=e.find(0,!0);r=i.from.line;n+=i.from.ch-i.to.ch}r=t;for(;e=Kr(r);){var i=e.find(0,!0);n-=r.text.length-i.from.ch;r=i.to.line;n+=r.text.length-i.to.ch}return n}function h(t){var e=t.display,n=t.doc;e.maxLine=Ei(n,n.first);e.maxLineLength=f(e.maxLine);e.maxLineChanged=!0;n.iter(function(t){var n=f(t);if(n>e.maxLineLength){e.maxLineLength=n;e.maxLine=t}})}function d(t){var e=go(t.gutters,"CodeMirror-linenumbers");if(-1==e&&t.lineNumbers)t.gutters=t.gutters.concat(["CodeMirror-linenumbers"]);else if(e>-1&&!t.lineNumbers){t.gutters=t.gutters.slice(0);t.gutters.splice(e,1)}}function p(t){return t.display.scroller.clientHeight-t.display.wrapper.clientHeight<ds-3}function g(t){var e=t.display.scroller;return{clientHeight:e.clientHeight,barHeight:t.display.scrollbarV.clientHeight,scrollWidth:e.scrollWidth,clientWidth:e.clientWidth,hScrollbarTakesSpace:p(t),barWidth:t.display.scrollbarH.clientWidth,docHeight:Math.round(t.doc.height+_e(t.display))}}function m(t,e){e||(e=g(t));var n=t.display,r=jo(n.measure),i=e.docHeight+ds,o=e.scrollWidth>e.clientWidth;o&&e.scrollWidth<=e.clientWidth+1&&r>0&&!e.hScrollbarTakesSpace&&(o=!1);var a=i>e.clientHeight;if(a){n.scrollbarV.style.display="block";n.scrollbarV.style.bottom=o?r+"px":"0";n.scrollbarV.firstChild.style.height=Math.max(0,i-e.clientHeight+(e.barHeight||n.scrollbarV.clientHeight))+"px"}else{n.scrollbarV.style.display="";n.scrollbarV.firstChild.style.height="0"}if(o){n.scrollbarH.style.display="block";n.scrollbarH.style.right=a?r+"px":"0";n.scrollbarH.firstChild.style.width=e.scrollWidth-e.clientWidth+(e.barWidth||n.scrollbarH.clientWidth)+"px"}else{n.scrollbarH.style.display="";n.scrollbarH.firstChild.style.width="0"}if(o&&a){n.scrollbarFiller.style.display="block";n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"}else n.scrollbarFiller.style.display="";if(o&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter){n.gutterFiller.style.display="block";n.gutterFiller.style.height=r+"px";n.gutterFiller.style.width=n.gutters.offsetWidth+"px"}else n.gutterFiller.style.display="";if(!t.state.checkedOverlayScrollbar&&e.clientHeight>0){if(0===r){var s=fa&&!sa?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=s;var l=function(e){no(e)!=n.scrollbarV&&no(e)!=n.scrollbarH&&un(t,En)(e)};us(n.scrollbarV,"mousedown",l);us(n.scrollbarH,"mousedown",l)}t.state.checkedOverlayScrollbar=!0}}function v(t,e,n){var r=n&&null!=n.top?Math.max(0,n.top):t.scroller.scrollTop;r=Math.floor(r-ke(t));var i=n&&null!=n.bottom?n.bottom:r+t.wrapper.clientHeight,o=Oi(e,r),a=Oi(e,i);if(n&&n.ensure){var s=n.ensure.from.line,l=n.ensure.to.line;if(o>s)return{from:s,to:Oi(e,Fi(Ei(e,s))+t.wrapper.clientHeight)};if(Math.min(l,e.lastLine())>=a)return{from:Oi(e,Fi(Ei(e,l))-t.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(a,o+1)}}function y(t){var e=t.display,n=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var r=w(e)-e.scroller.scrollLeft+t.doc.scrollLeft,i=e.gutters.offsetWidth,o=r+"px",a=0;a<n.length;a++)if(!n[a].hidden){t.options.fixedGutter&&n[a].gutter&&(n[a].gutter.style.left=o);var s=n[a].alignable;if(s)for(var l=0;l<s.length;l++)s[l].style.left=o}t.options.fixedGutter&&(e.gutters.style.left=r+i+"px")}}function b(t){if(!t.options.lineNumbers)return!1;var e=t.doc,n=x(t.options,e.first+e.size-1),r=t.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(So("div",[So("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,a=i.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-a);r.lineNumWidth=r.lineNumInnerWidth+a;r.lineNumChars=r.lineNumInnerWidth?n.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";c(t);return!0}return!1}function x(t,e){return String(t.lineNumberFormatter(e+t.firstLineNumber))}function w(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function C(t,e,n){var r=t.display;this.viewport=e;this.visible=v(r,t.doc,e);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldViewFrom=r.viewFrom;this.oldViewTo=r.viewTo;this.oldScrollerWidth=r.scroller.clientWidth;this.force=n;this.dims=A(t)}function S(t,e){var n=t.display,r=t.doc;if(e.editorIsHidden){mn(t);return!1}if(!e.force&&e.visible.from>=n.viewFrom&&e.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&0==xn(t))return!1;if(b(t)){mn(t);e.dims=A(t)}var i=r.first+r.size,o=Math.max(e.visible.from-t.options.viewportMargin,r.first),a=Math.min(i,e.visible.to+t.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom));n.viewTo>a&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo));if(va){o=ei(t.doc,o);a=ni(t.doc,a)}var s=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=e.wrapperHeight||n.lastWrapWidth!=e.wrapperWidth;bn(t,o,a);n.viewOffset=Fi(Ei(t.doc,n.viewFrom));t.display.mover.style.top=n.viewOffset+"px";var l=xn(t);if(!s&&0==l&&!e.force&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=Mo();l>4&&(n.lineDiv.style.display="none");N(t,n.updateLineNumbers,e.dims);l>4&&(n.lineDiv.style.display="");u&&Mo()!=u&&u.offsetHeight&&u.focus();To(n.cursorDiv);To(n.selectionDiv);if(s){n.lastWrapHeight=e.wrapperHeight;n.lastWrapWidth=e.wrapperWidth;we(t,400)}n.updateLineNumbers=null;return!0}function T(t,e){for(var n=e.force,r=e.viewport,i=!0;;i=!1){if(i&&t.options.lineWrapping&&e.oldScrollerWidth!=t.display.scroller.clientWidth)n=!0;else{n=!1;r&&null!=r.top&&(r={top:Math.min(t.doc.height+_e(t.display)-ds-t.display.scroller.clientHeight,r.top)});e.visible=v(t.display,t.doc,r);if(e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)break}if(!S(t,e))break;D(t);var o=g(t);ve(t);_(t,o);m(t,o)}io(t,"update",t);(t.display.viewFrom!=e.oldViewFrom||t.display.viewTo!=e.oldViewTo)&&io(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo)}function k(t,e){var n=new C(t,e);if(S(t,n)){D(t);T(t,n);var r=g(t);ve(t);_(t,r);m(t,r)}}function _(t,e){t.display.sizer.style.minHeight=t.display.heightForcer.style.top=e.docHeight+"px";t.display.gutters.style.height=Math.max(e.docHeight,e.clientHeight-ds)+"px"}function M(t,e){if(t.display.sizer.offsetWidth+t.display.gutters.offsetWidth<t.display.scroller.clientWidth-1){t.display.sizer.style.minHeight=t.display.heightForcer.style.top="0px";t.display.gutters.style.height=e.docHeight+"px"}}function D(t){for(var e=t.display,n=e.lineDiv.offsetTop,r=0;r<e.view.length;r++){var i,o=e.view[r];if(!o.hidden){if(Qo&&8>ta){var a=o.node.offsetTop+o.node.offsetHeight;i=a-n;n=a}else{var s=o.node.getBoundingClientRect();i=s.bottom-s.top}var l=o.line.height-i;2>i&&(i=Je(e));if(l>.001||-.001>l){Pi(o.line,i);L(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)L(o.rest[u])}}}}function L(t){if(t.widgets)for(var e=0;e<t.widgets.length;++e)t.widgets[e].height=t.widgets[e].node.offsetHeight}function A(t){for(var e=t.display,n={},r={},i=e.gutters.clientLeft,o=e.gutters.firstChild,a=0;o;o=o.nextSibling,++a){n[t.options.gutters[a]]=o.offsetLeft+o.clientLeft+i;r[t.options.gutters[a]]=o.clientWidth}return{fixedPos:w(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:e.wrapper.clientWidth}}function N(t,e,n){function r(e){var n=e.nextSibling;ea&&fa&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e);return n}for(var i=t.display,o=t.options.lineNumbers,a=i.lineDiv,s=a.firstChild,l=i.view,u=i.viewFrom,c=0;c<l.length;c++){var f=l[c];if(f.hidden);else if(f.node){for(;s!=f.node;)s=r(s);var h=o&&null!=e&&u>=e&&f.lineNumber;if(f.changes){go(f.changes,"gutter")>-1&&(h=!1);E(t,f,u,n)}if(h){To(f.lineNumber);f.lineNumber.appendChild(document.createTextNode(x(t.options,u)))}s=f.node.nextSibling}else{var d=W(t,f,u,n);a.insertBefore(d,s)}u+=f.size}for(;s;)s=r(s)}function E(t,e,n,r){for(var i=0;i<e.changes.length;i++){var o=e.changes[i];"text"==o?H(t,e):"gutter"==o?F(t,e,n,r):"class"==o?O(e):"widget"==o&&R(e,r)}e.changes=null}function j(t){if(t.node==t.text){t.node=So("div",null,null,"position: relative");t.text.parentNode&&t.text.parentNode.replaceChild(t.node,t.text);t.node.appendChild(t.text);Qo&&8>ta&&(t.node.style.zIndex=2)}return t.node}function I(t){var e=t.bgClass?t.bgClass+" "+(t.line.bgClass||""):t.line.bgClass;e&&(e+=" CodeMirror-linebackground");if(t.background)if(e)t.background.className=e;else{t.background.parentNode.removeChild(t.background);t.background=null}else if(e){var n=j(t);t.background=n.insertBefore(So("div",null,e),n.firstChild)}}function P(t,e){var n=t.display.externalMeasured;if(n&&n.line==e.line){t.display.externalMeasured=null;e.measure=n.measure;return n.built}return bi(t,e)}function H(t,e){var n=e.text.className,r=P(t,e);e.text==e.node&&(e.node=r.pre);e.text.parentNode.replaceChild(r.pre,e.text);e.text=r.pre;if(r.bgClass!=e.bgClass||r.textClass!=e.textClass){e.bgClass=r.bgClass;e.textClass=r.textClass;O(e)}else n&&(e.text.className=n)}function O(t){I(t);t.line.wrapClass?j(t).className=t.line.wrapClass:t.node!=t.text&&(t.node.className="");var e=t.textClass?t.textClass+" "+(t.line.textClass||""):t.line.textClass;t.text.className=e||""}function F(t,e,n,r){if(e.gutter){e.node.removeChild(e.gutter);e.gutter=null}var i=e.line.gutterMarkers;if(t.options.lineNumbers||i){var o=j(e),a=e.gutter=o.insertBefore(So("div",null,"CodeMirror-gutter-wrapper","left: "+(t.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),e.text);e.line.gutterClass&&(a.className+=" "+e.line.gutterClass);!t.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(e.lineNumber=a.appendChild(So("div",x(t.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+t.display.lineNumInnerWidth+"px")));if(i)for(var s=0;s<t.options.gutters.length;++s){var l=t.options.gutters[s],u=i.hasOwnProperty(l)&&i[l];u&&a.appendChild(So("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function R(t,e){t.alignable&&(t.alignable=null);for(var n,r=t.node.firstChild;r;r=n){var n=r.nextSibling;"CodeMirror-linewidget"==r.className&&t.node.removeChild(r)}z(t,e)}function W(t,e,n,r){var i=P(t,e);e.text=e.node=i.pre;i.bgClass&&(e.bgClass=i.bgClass);i.textClass&&(e.textClass=i.textClass);O(e);F(t,e,n,r);z(e,r);return e.node}function z(t,e){q(t.line,t,e,!0);if(t.rest)for(var n=0;n<t.rest.length;n++)q(t.rest[n],t,e,!1)}function q(t,e,n,r){if(t.widgets)for(var i=j(e),o=0,a=t.widgets;o<a.length;++o){var s=a[o],l=So("div",[s.node],"CodeMirror-linewidget");s.handleMouseEvents||(l.ignoreEvents=!0);U(s,l,e,n);r&&s.above?i.insertBefore(l,e.gutter||e.text):i.appendChild(l);io(s,"redraw")}}function U(t,e,n,r){if(t.noHScroll){(n.alignable||(n.alignable=[])).push(e);var i=r.wrapperWidth;e.style.left=r.fixedPos+"px";if(!t.coverGutter){i-=r.gutterTotalWidth;e.style.paddingLeft=r.gutterTotalWidth+"px"}e.style.width=i+"px"}if(t.coverGutter){e.style.zIndex=5;e.style.position="relative";t.noHScroll||(e.style.marginLeft=-r.gutterTotalWidth+"px")}}function B(t){return ya(t.line,t.ch)}function V(t,e){return ba(t,e)<0?e:t}function X(t,e){return ba(t,e)<0?t:e}function G(t,e){this.ranges=t;this.primIndex=e}function $(t,e){this.anchor=t;this.head=e}function Y(t,e){var n=t[e];t.sort(function(t,e){return ba(t.from(),e.from())});e=go(t,n);for(var r=1;r<t.length;r++){var i=t[r],o=t[r-1];if(ba(o.to(),i.from())>=0){var a=X(o.from(),i.from()),s=V(o.to(),i.to()),l=o.empty()?i.from()==i.head:o.from()==o.head;e>=r&&--e;t.splice(--r,2,new $(l?s:a,l?a:s))}}return new G(t,e)}function J(t,e){return new G([new $(t,e||t)],0)}function K(t,e){return Math.max(t.first,Math.min(e,t.first+t.size-1))}function Z(t,e){if(e.line<t.first)return ya(t.first,0);var n=t.first+t.size-1;return e.line>n?ya(n,Ei(t,n).text.length):Q(e,Ei(t,e.line).text.length)}function Q(t,e){var n=t.ch;return null==n||n>e?ya(t.line,e):0>n?ya(t.line,0):t}function te(t,e){return e>=t.first&&e<t.first+t.size}function ee(t,e){for(var n=[],r=0;r<e.length;r++)n[r]=Z(t,e[r]);return n}function ne(t,e,n,r){if(t.cm&&t.cm.display.shift||t.extend){var i=e.anchor;if(r){var o=ba(n,i)<0;if(o!=ba(r,i)<0){i=n;n=r}else o!=ba(n,r)<0&&(n=r)}return new $(i,n)}return new $(r||n,n)}function re(t,e,n,r){ue(t,new G([ne(t,t.sel.primary(),e,n)],0),r)}function ie(t,e,n){for(var r=[],i=0;i<t.sel.ranges.length;i++)r[i]=ne(t,t.sel.ranges[i],e[i],null);var o=Y(r,t.sel.primIndex);ue(t,o,n)}function oe(t,e,n,r){var i=t.sel.ranges.slice(0);i[e]=n;ue(t,Y(i,t.sel.primIndex),r)}function ae(t,e,n,r){ue(t,J(e,n),r)}function se(t,e){var n={ranges:e.ranges,update:function(e){this.ranges=[];for(var n=0;n<e.length;n++)this.ranges[n]=new $(Z(t,e[n].anchor),Z(t,e[n].head))}};fs(t,"beforeSelectionChange",t,n);t.cm&&fs(t.cm,"beforeSelectionChange",t.cm,n);return n.ranges!=e.ranges?Y(n.ranges,n.ranges.length-1):e}function le(t,e,n){var r=t.history.done,i=po(r);if(i&&i.ranges){r[r.length-1]=e;ce(t,e,n)}else ue(t,e,n)}function ue(t,e,n){ce(t,e,n);Xi(t,t.sel,t.cm?t.cm.curOp.id:0/0,n)}function ce(t,e,n){(lo(t,"beforeSelectionChange")||t.cm&&lo(t.cm,"beforeSelectionChange"))&&(e=se(t,e));var r=n&&n.bias||(ba(e.primary().head,t.sel.primary().head)<0?-1:1);fe(t,de(t,e,r,!0));n&&n.scroll===!1||!t.cm||br(t.cm)}function fe(t,e){if(!e.equals(t.sel)){t.sel=e;if(t.cm){t.cm.curOp.updateInput=t.cm.curOp.selectionChanged=!0;so(t.cm)}io(t,"cursorActivity",t)}}function he(t){fe(t,de(t,t.sel,null,!1),gs)}function de(t,e,n,r){for(var i,o=0;o<e.ranges.length;o++){var a=e.ranges[o],s=pe(t,a.anchor,n,r),l=pe(t,a.head,n,r);if(i||s!=a.anchor||l!=a.head){i||(i=e.ranges.slice(0,o));i[o]=new $(s,l)}}return i?Y(i,e.primIndex):e}function pe(t,e,n,r){var i=!1,o=e,a=n||1;t.cantEdit=!1;t:for(;;){var s=Ei(t,o.line);if(s.markedSpans)for(var l=0;l<s.markedSpans.length;++l){var u=s.markedSpans[l],c=u.marker;if((null==u.from||(c.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(c.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){fs(c,"beforeCursorEnter");if(c.explicitlyCleared){if(s.markedSpans){--l;continue}break}}if(!c.atomic)continue;var f=c.find(0>a?-1:1);if(0==ba(f,o)){f.ch+=a;f.ch<0?f=f.line>t.first?Z(t,ya(f.line-1)):null:f.ch>s.text.length&&(f=f.line<t.first+t.size-1?ya(f.line+1,0):null);if(!f){if(i){if(!r)return pe(t,e,n,!0);t.cantEdit=!0;return ya(t.first,0)}i=!0;f=e;a=-a}}o=f;continue t}}return o}}function ge(t){for(var e=t.display,n=t.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),a=0;a<n.sel.ranges.length;a++){var s=n.sel.ranges[a],l=s.empty();(l||t.options.showCursorWhenSelecting)&&ye(t,s,i);l||be(t,s,o)}if(t.options.moveInputWithCursor){var u=Ve(t,n.sel.primary().head,"div"),c=e.wrapper.getBoundingClientRect(),f=e.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,u.top+f.top-c.top));r.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,u.left+f.left-c.left))}return r}function me(t,e){ko(t.display.cursorDiv,e.cursors);ko(t.display.selectionDiv,e.selection);if(null!=e.teTop){t.display.inputDiv.style.top=e.teTop+"px";t.display.inputDiv.style.left=e.teLeft+"px"}}function ve(t){me(t,ge(t))}function ye(t,e,n){var r=Ve(t,e.head,"div",null,null,!t.options.singleCursorHeightPerLine),i=n.appendChild(So("div"," ","CodeMirror-cursor"));i.style.left=r.left+"px";i.style.top=r.top+"px";i.style.height=Math.max(0,r.bottom-r.top)*t.options.cursorHeight+"px";if(r.other){var o=n.appendChild(So("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function be(t,e,n){function r(t,e,n,r){0>e&&(e=0);e=Math.round(e);r=Math.round(r);s.appendChild(So("div",null,"CodeMirror-selected","position: absolute; left: "+t+"px; top: "+e+"px; width: "+(null==n?c-t:n)+"px; height: "+(r-e)+"px"))}function i(e,n,i){function o(n,r){return Be(t,ya(e,n),"div",f,r)}var s,l,f=Ei(a,e),h=f.text.length;Oo(Ri(f),n||0,null==i?h:i,function(t,e,a){var f,d,p,g=o(t,"left");if(t==e){f=g;d=p=g.left}else{f=o(e-1,"right");if("rtl"==a){var m=g;g=f;f=m}d=g.left;p=f.right}null==n&&0==t&&(d=u);if(f.top-g.top>3){r(d,g.top,null,g.bottom);d=u;g.bottom<f.top&&r(d,g.bottom,null,f.top)}null==i&&e==h&&(p=c);(!s||g.top<s.top||g.top==s.top&&g.left<s.left)&&(s=g);(!l||f.bottom>l.bottom||f.bottom==l.bottom&&f.right>l.right)&&(l=f);u+1>d&&(d=u);r(d,f.top,p-d,f.bottom)});return{start:s,end:l}}var o=t.display,a=t.doc,s=document.createDocumentFragment(),l=Me(t.display),u=l.left,c=o.lineSpace.offsetWidth-l.right,f=e.from(),h=e.to();if(f.line==h.line)i(f.line,f.ch,h.ch);else{var d=Ei(a,f.line),p=Ei(a,h.line),g=Qr(d)==Qr(p),m=i(f.line,f.ch,g?d.text.length+1:null).end,v=i(h.line,g?0:null,h.ch).start;if(g)if(m.top<v.top-2){r(m.right,m.top,null,m.bottom);r(u,v.top,v.left,v.bottom)}else r(m.right,m.top,v.left-m.right,m.bottom);m.bottom<v.top&&r(u,m.bottom,null,v.top)}n.appendChild(s)}function xe(t){if(t.state.focused){var e=t.display;clearInterval(e.blinker);var n=!0;e.cursorDiv.style.visibility="";t.options.cursorBlinkRate>0?e.blinker=setInterval(function(){e.cursorDiv.style.visibility=(n=!n)?"":"hidden"},t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden")}}function we(t,e){t.doc.mode.startState&&t.doc.frontier<t.display.viewTo&&t.state.highlight.set(e,bo(Ce,t))}function Ce(t){var e=t.doc;e.frontier<e.first&&(e.frontier=e.first);if(!(e.frontier>=t.display.viewTo)){var n=+new Date+t.options.workTime,r=za(e.mode,Te(t,e.frontier)),i=[];e.iter(e.frontier,Math.min(e.first+e.size,t.display.viewTo+500),function(o){if(e.frontier>=t.display.viewFrom){var a=o.styles,s=gi(t,o,r,!0);o.styles=s.styles;var l=o.styleClasses,u=s.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var c=!a||a.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),f=0;!c&&f<a.length;++f)c=a[f]!=o.styles[f];c&&i.push(e.frontier);o.stateAfter=za(e.mode,r)}else{vi(t,o.text,r);o.stateAfter=e.frontier%5==0?za(e.mode,r):null}++e.frontier;if(+new Date>n){we(t,t.options.workDelay);return!0}});i.length&&ln(t,function(){for(var e=0;e<i.length;e++)gn(t,i[e],"text")})}}function Se(t,e,n){for(var r,i,o=t.doc,a=n?-1:e-(t.doc.mode.innerMode?1e3:100),s=e;s>a;--s){if(s<=o.first)return o.first;var l=Ei(o,s-1);if(l.stateAfter&&(!n||s<=o.frontier))return s;var u=ys(l.text,null,t.options.tabSize);if(null==i||r>u){i=s-1;r=u}}return i}function Te(t,e,n){var r=t.doc,i=t.display;if(!r.mode.startState)return!0;var o=Se(t,e,n),a=o>r.first&&Ei(r,o-1).stateAfter;a=a?za(r.mode,a):qa(r.mode);r.iter(o,e,function(n){vi(t,n.text,a);var s=o==e-1||o%5==0||o>=i.viewFrom&&o<i.viewTo;n.stateAfter=s?za(r.mode,a):null;++o});n&&(r.frontier=o);return a}function ke(t){return t.lineSpace.offsetTop}function _e(t){return t.mover.offsetHeight-t.lineSpace.offsetHeight}function Me(t){if(t.cachedPaddingH)return t.cachedPaddingH;var e=ko(t.measure,So("pre","x")),n=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};isNaN(r.left)||isNaN(r.right)||(t.cachedPaddingH=r);return r}function De(t,e,n){var r=t.options.lineWrapping,i=r&&t.display.scroller.clientWidth;if(!e.measure.heights||r&&e.measure.width!=i){var o=e.measure.heights=[];if(r){e.measure.width=i;for(var a=e.text.firstChild.getClientRects(),s=0;s<a.length-1;s++){var l=a[s],u=a[s+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-n.top)}}o.push(n.bottom-n.top)}}function Le(t,e,n){if(t.line==e)return{map:t.measure.map,cache:t.measure.cache};for(var r=0;r<t.rest.length;r++)if(t.rest[r]==e)return{map:t.measure.maps[r],cache:t.measure.caches[r]};for(var r=0;r<t.rest.length;r++)if(Hi(t.rest[r])>n)return{map:t.measure.maps[r],cache:t.measure.caches[r],before:!0}}function Ae(t,e){e=Qr(e);var n=Hi(e),r=t.display.externalMeasured=new hn(t.doc,e,n);r.lineN=n;var i=r.built=bi(t,r);r.text=i.pre;ko(t.display.lineMeasure,i.pre);return r}function Ne(t,e,n,r){return Ie(t,je(t,e),n,r)}function Ee(t,e){if(e>=t.display.viewFrom&&e<t.display.viewTo)return t.display.view[vn(t,e)];var n=t.display.externalMeasured;return n&&e>=n.lineN&&e<n.lineN+n.size?n:void 0}function je(t,e){var n=Hi(e),r=Ee(t,n);r&&!r.text?r=null:r&&r.changes&&E(t,r,n,A(t));r||(r=Ae(t,e));var i=Le(r,e,n);return{line:e,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Ie(t,e,n,r,i){e.before&&(n=-1);var o,a=n+(r||"");if(e.cache.hasOwnProperty(a))o=e.cache[a];else{e.rect||(e.rect=e.view.text.getBoundingClientRect());if(!e.hasHeights){De(t,e.view,e.rect);e.hasHeights=!0}o=Pe(t,e,n,r);o.bogus||(e.cache[a]=o)}return{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}function Pe(t,e,n,r){for(var i,o,a,s,l=e.map,u=0;u<l.length;u+=3){var c=l[u],f=l[u+1]; if(c>n){o=0;a=1;s="left"}else if(f>n){o=n-c;a=o+1}else if(u==l.length-3||n==f&&l[u+3]>n){a=f-c;o=a-1;n>=f&&(s="right")}if(null!=o){i=l[u+2];c==f&&r==(i.insertLeft?"left":"right")&&(s=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){i=l[(u-=3)+2];s="left"}if("right"==r&&o==f-c)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){i=l[(u+=3)+2];s="right"}break}}var h;if(3==i.nodeType){for(var u=0;4>u;u++){for(;o&&Co(e.line.text.charAt(c+o));)--o;for(;f>c+a&&Co(e.line.text.charAt(c+a));)++a;if(Qo&&9>ta&&0==o&&a==f-c)h=i.parentNode.getBoundingClientRect();else if(Qo&&t.options.lineWrapping){var d=ws(i,o,a).getClientRects();h=d.length?d["right"==r?d.length-1:0]:Sa}else h=ws(i,o,a).getBoundingClientRect()||Sa;if(h.left||h.right||0==o)break;a=o;o-=1;s="right"}Qo&&11>ta&&(h=He(t.display.measure,h))}else{o>0&&(s=r="right");var d;h=t.options.lineWrapping&&(d=i.getClientRects()).length>1?d["right"==r?d.length-1:0]:i.getBoundingClientRect()}if(Qo&&9>ta&&!o&&(!h||!h.left&&!h.right)){var p=i.parentNode.getClientRects()[0];h=p?{left:p.left,right:p.left+Ke(t.display),top:p.top,bottom:p.bottom}:Sa}for(var g=h.top-e.rect.top,m=h.bottom-e.rect.top,v=(g+m)/2,y=e.view.measure.heights,u=0;u<y.length-1&&!(v<y[u]);u++);var b=u?y[u-1]:0,x=y[u],w={left:("right"==s?h.right:h.left)-e.rect.left,right:("left"==s?h.left:h.right)-e.rect.left,top:b,bottom:x};h.left||h.right||(w.bogus=!0);if(!t.options.singleCursorHeightPerLine){w.rtop=g;w.rbottom=m}return w}function He(t,e){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Ho(t))return e;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:e.left*n,right:e.right*n,top:e.top*r,bottom:e.bottom*r}}function Oe(t){if(t.measure){t.measure.cache={};t.measure.heights=null;if(t.rest)for(var e=0;e<t.rest.length;e++)t.measure.caches[e]={}}}function Fe(t){t.display.externalMeasure=null;To(t.display.lineMeasure);for(var e=0;e<t.display.view.length;e++)Oe(t.display.view[e])}function Re(t){Fe(t);t.display.cachedCharWidth=t.display.cachedTextHeight=t.display.cachedPaddingH=null;t.options.lineWrapping||(t.display.maxLineChanged=!0);t.display.lineNumChars=null}function We(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function ze(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function qe(t,e,n,r){if(e.widgets)for(var i=0;i<e.widgets.length;++i)if(e.widgets[i].above){var o=ai(e.widgets[i]);n.top+=o;n.bottom+=o}if("line"==r)return n;r||(r="local");var a=Fi(e);"local"==r?a+=ke(t.display):a-=t.display.viewOffset;if("page"==r||"window"==r){var s=t.display.lineSpace.getBoundingClientRect();a+=s.top+("window"==r?0:ze());var l=s.left+("window"==r?0:We());n.left+=l;n.right+=l}n.top+=a;n.bottom+=a;return n}function Ue(t,e,n){if("div"==n)return e;var r=e.left,i=e.top;if("page"==n){r-=We();i-=ze()}else if("local"==n||!n){var o=t.display.sizer.getBoundingClientRect();r+=o.left;i+=o.top}var a=t.display.lineSpace.getBoundingClientRect();return{left:r-a.left,top:i-a.top}}function Be(t,e,n,r,i){r||(r=Ei(t.doc,e.line));return qe(t,r,Ne(t,r,e.ch,i),n)}function Ve(t,e,n,r,i,o){function a(e,a){var s=Ie(t,i,e,a?"right":"left",o);a?s.left=s.right:s.right=s.left;return qe(t,r,s,n)}function s(t,e){var n=l[e],r=n.level%2;if(t==Fo(n)&&e&&n.level<l[e-1].level){n=l[--e];t=Ro(n)-(n.level%2?0:1);r=!0}else if(t==Ro(n)&&e<l.length-1&&n.level<l[e+1].level){n=l[++e];t=Fo(n)-n.level%2;r=!1}return r&&t==n.to&&t>n.from?a(t-1):a(t,r)}r=r||Ei(t.doc,e.line);i||(i=je(t,r));var l=Ri(r),u=e.ch;if(!l)return a(u);var c=Xo(l,u),f=s(u,c);null!=Os&&(f.other=s(u,Os));return f}function Xe(t,e){var n=0,e=Z(t.doc,e);t.options.lineWrapping||(n=Ke(t.display)*e.ch);var r=Ei(t.doc,e.line),i=Fi(r)+ke(t.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Ge(t,e,n,r){var i=ya(t,e);i.xRel=r;n&&(i.outside=!0);return i}function $e(t,e,n){var r=t.doc;n+=t.display.viewOffset;if(0>n)return Ge(r.first,0,!0,-1);var i=Oi(r,n),o=r.first+r.size-1;if(i>o)return Ge(r.first+r.size-1,Ei(r,o).text.length,!0,1);0>e&&(e=0);for(var a=Ei(r,i);;){var s=Ye(t,a,i,e,n),l=Kr(a),u=l&&l.find(0,!0);if(!l||!(s.ch>u.from.ch||s.ch==u.from.ch&&s.xRel>0))return s;i=Hi(a=u.to.line)}}function Ye(t,e,n,r,i){function o(r){var i=Ve(t,ya(n,r),"line",e,u);s=!0;if(a>i.bottom)return i.left-l;if(a<i.top)return i.left+l;s=!1;return i.left}var a=i-Fi(e),s=!1,l=2*t.display.wrapper.clientWidth,u=je(t,e),c=Ri(e),f=e.text.length,h=Wo(e),d=zo(e),p=o(h),g=s,m=o(d),v=s;if(r>m)return Ge(n,d,v,1);for(;;){if(c?d==h||d==$o(e,h,1):1>=d-h){for(var y=p>r||m-r>=r-p?h:d,b=r-(y==h?p:m);Co(e.text.charAt(y));)++y;var x=Ge(n,y,y==h?g:v,-1>b?-1:b>1?1:0);return x}var w=Math.ceil(f/2),C=h+w;if(c){C=h;for(var S=0;w>S;++S)C=$o(e,C,1)}var T=o(C);if(T>r){d=C;m=T;(v=s)&&(m+=1e3);f=w}else{h=C;p=T;g=s;f-=w}}}function Je(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==xa){xa=So("pre");for(var e=0;49>e;++e){xa.appendChild(document.createTextNode("x"));xa.appendChild(So("br"))}xa.appendChild(document.createTextNode("x"))}ko(t.measure,xa);var n=xa.offsetHeight/50;n>3&&(t.cachedTextHeight=n);To(t.measure);return n||1}function Ke(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=So("span","xxxxxxxxxx"),n=So("pre",[e]);ko(t.measure,n);var r=e.getBoundingClientRect(),i=(r.right-r.left)/10;i>2&&(t.cachedCharWidth=i);return i||10}function Ze(t){t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++ka};Ta?Ta.ops.push(t.curOp):t.curOp.ownsGroup=Ta={ops:[t.curOp],delayedCallbacks:[]}}function Qe(t){var e=t.delayedCallbacks,n=0;do{for(;n<e.length;n++)e[n]();for(var r=0;r<t.ops.length;r++){var i=t.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++](i.cm)}}while(n<e.length)}function tn(t){var e=t.curOp,n=e.ownsGroup;if(n)try{Qe(n)}finally{Ta=null;for(var r=0;r<n.ops.length;r++)n.ops[r].cm.curOp=null;en(n)}}function en(t){for(var e=t.ops,n=0;n<e.length;n++)nn(e[n]);for(var n=0;n<e.length;n++)rn(e[n]);for(var n=0;n<e.length;n++)on(e[n]);for(var n=0;n<e.length;n++)an(e[n]);for(var n=0;n<e.length;n++)sn(e[n])}function nn(t){var e=t.cm,n=e.display;t.updateMaxLine&&h(e);t.mustUpdate=t.viewChanged||t.forceUpdate||null!=t.scrollTop||t.scrollToPos&&(t.scrollToPos.from.line<n.viewFrom||t.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&e.options.lineWrapping;t.update=t.mustUpdate&&new C(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate)}function rn(t){t.updatedDisplay=t.mustUpdate&&S(t.cm,t.update)}function on(t){var e=t.cm,n=e.display;t.updatedDisplay&&D(e);t.barMeasure=g(e);if(n.maxLineChanged&&!e.options.lineWrapping){t.adjustWidthTo=Ne(e,n.maxLine,n.maxLine.text.length).left+3;t.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+t.adjustWidthTo+ds-n.scroller.clientWidth)}(t.updatedDisplay||t.selectionChanged)&&(t.newSelectionNodes=ge(e))}function an(t){var e=t.cm;if(null!=t.adjustWidthTo){e.display.sizer.style.minWidth=t.adjustWidthTo+"px";t.maxScrollLeft<e.doc.scrollLeft&&zn(e,Math.min(e.display.scroller.scrollLeft,t.maxScrollLeft),!0);e.display.maxLineChanged=!1}t.newSelectionNodes&&me(e,t.newSelectionNodes);t.updatedDisplay&&_(e,t.barMeasure);(t.updatedDisplay||t.startHeight!=e.doc.height)&&m(e,t.barMeasure);t.selectionChanged&&xe(e);e.state.focused&&t.updateInput&&Tn(e,t.typing)}function sn(t){var e=t.cm,n=e.display,r=e.doc;null!=t.adjustWidthTo&&Math.abs(t.barMeasure.scrollWidth-e.display.scroller.scrollWidth)>1&&m(e);t.updatedDisplay&&T(e,t.update);null==n.wheelStartX||null==t.scrollTop&&null==t.scrollLeft&&!t.scrollToPos||(n.wheelStartX=n.wheelStartY=null);if(null!=t.scrollTop&&(n.scroller.scrollTop!=t.scrollTop||t.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,t.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(null!=t.scrollLeft&&(n.scroller.scrollLeft!=t.scrollLeft||t.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,t.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o;y(e)}if(t.scrollToPos){var a=gr(e,Z(r,t.scrollToPos.from),Z(r,t.scrollToPos.to),t.scrollToPos.margin);t.scrollToPos.isCursor&&e.state.focused&&pr(e,a)}var s=t.maybeHiddenMarkers,l=t.maybeUnhiddenMarkers;if(s)for(var u=0;u<s.length;++u)s[u].lines.length||fs(s[u],"hide");if(l)for(var u=0;u<l.length;++u)l[u].lines.length&&fs(l[u],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=e.display.scroller.scrollTop);if(t.updatedDisplay&&ea){e.options.lineWrapping&&M(e,t.barMeasure);t.barMeasure.scrollWidth>t.barMeasure.clientWidth&&t.barMeasure.scrollWidth<t.barMeasure.clientWidth+1&&!p(e)&&m(e)}t.changeObjs&&fs(e,"changes",e,t.changeObjs)}function ln(t,e){if(t.curOp)return e();Ze(t);try{return e()}finally{tn(t)}}function un(t,e){return function(){if(t.curOp)return e.apply(t,arguments);Ze(t);try{return e.apply(t,arguments)}finally{tn(t)}}}function cn(t){return function(){if(this.curOp)return t.apply(this,arguments);Ze(this);try{return t.apply(this,arguments)}finally{tn(this)}}}function fn(t){return function(){var e=this.cm;if(!e||e.curOp)return t.apply(this,arguments);Ze(e);try{return t.apply(this,arguments)}finally{tn(e)}}}function hn(t,e,n){this.line=e;this.rest=ti(e);this.size=this.rest?Hi(po(this.rest))-n+1:1;this.node=this.text=null;this.hidden=ri(t,e)}function dn(t,e,n){for(var r,i=[],o=e;n>o;o=r){var a=new hn(t.doc,Ei(t.doc,o),o);r=o+a.size;i.push(a)}return i}function pn(t,e,n,r){null==e&&(e=t.doc.first);null==n&&(n=t.doc.first+t.doc.size);r||(r=0);var i=t.display;r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>e)&&(i.updateLineNumbers=e);t.curOp.viewChanged=!0;if(e>=i.viewTo)va&&ei(t.doc,e)<i.viewTo&&mn(t);else if(n<=i.viewFrom)if(va&&ni(t.doc,n+r)>i.viewFrom)mn(t);else{i.viewFrom+=r;i.viewTo+=r}else if(e<=i.viewFrom&&n>=i.viewTo)mn(t);else if(e<=i.viewFrom){var o=yn(t,n,n+r,1);if(o){i.view=i.view.slice(o.index);i.viewFrom=o.lineN;i.viewTo+=r}else mn(t)}else if(n>=i.viewTo){var o=yn(t,e,e,-1);if(o){i.view=i.view.slice(0,o.index);i.viewTo=o.lineN}else mn(t)}else{var a=yn(t,e,e,-1),s=yn(t,n,n+r,1);if(a&&s){i.view=i.view.slice(0,a.index).concat(dn(t,a.lineN,s.lineN)).concat(i.view.slice(s.index));i.viewTo+=r}else mn(t)}var l=i.externalMeasured;l&&(n<l.lineN?l.lineN+=r:e<l.lineN+l.size&&(i.externalMeasured=null))}function gn(t,e,n){t.curOp.viewChanged=!0;var r=t.display,i=t.display.externalMeasured;i&&e>=i.lineN&&e<i.lineN+i.size&&(r.externalMeasured=null);if(!(e<r.viewFrom||e>=r.viewTo)){var o=r.view[vn(t,e)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==go(a,n)&&a.push(n)}}}function mn(t){t.display.viewFrom=t.display.viewTo=t.doc.first;t.display.view=[];t.display.viewOffset=0}function vn(t,e){if(e>=t.display.viewTo)return null;e-=t.display.viewFrom;if(0>e)return null;for(var n=t.display.view,r=0;r<n.length;r++){e-=n[r].size;if(0>e)return r}}function yn(t,e,n,r){var i,o=vn(t,e),a=t.display.view;if(!va||n==t.doc.first+t.doc.size)return{index:o,lineN:n};for(var s=0,l=t.display.viewFrom;o>s;s++)l+=a[s].size;if(l!=e){if(r>0){if(o==a.length-1)return null;i=l+a[o].size-e;o++}else i=l-e;e+=i;n+=i}for(;ei(t.doc,n)!=n;){if(o==(0>r?0:a.length-1))return null;n+=r*a[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:n}}function bn(t,e,n){var r=t.display,i=r.view;if(0==i.length||e>=r.viewTo||n<=r.viewFrom){r.view=dn(t,e,n);r.viewFrom=e}else{r.viewFrom>e?r.view=dn(t,e,r.viewFrom).concat(r.view):r.viewFrom<e&&(r.view=r.view.slice(vn(t,e)));r.viewFrom=e;r.viewTo<n?r.view=r.view.concat(dn(t,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,vn(t,n)))}r.viewTo=n}function xn(t){for(var e=t.display.view,n=0,r=0;r<e.length;r++){var i=e[r];i.hidden||i.node&&!i.changes||++n}return n}function wn(t){t.display.pollingFast||t.display.poll.set(t.options.pollInterval,function(){Sn(t);t.state.focused&&wn(t)})}function Cn(t){function e(){var r=Sn(t);if(r||n){t.display.pollingFast=!1;wn(t)}else{n=!0;t.display.poll.set(60,e)}}var n=!1;t.display.pollingFast=!0;t.display.poll.set(20,e)}function Sn(t){var e=t.display.input,n=t.display.prevInput,r=t.doc;if(!t.state.focused||js(e)&&!n||Mn(t)||t.options.disableInput||t.state.keySeq)return!1;if(t.state.pasteIncoming&&t.state.fakedLastChar){e.value=e.value.substring(0,e.value.length-1);t.state.fakedLastChar=!1}var i=e.value;if(i==n&&!t.somethingSelected())return!1;if(Qo&&ta>=9&&t.display.inputHasSelection===i||fa&&/[\uf700-\uf7ff]/.test(i)){Tn(t);return!1}var o=!t.curOp;o&&Ze(t);t.display.shift=!1;8203!=i.charCodeAt(0)||r.sel!=t.display.selForContextMenu||n||(n="​");for(var a=0,s=Math.min(n.length,i.length);s>a&&n.charCodeAt(a)==i.charCodeAt(a);)++a;var l=i.slice(a),u=Es(l),c=null;t.state.pasteIncoming&&r.sel.ranges.length>1&&(_a&&_a.join("\n")==l?c=r.sel.ranges.length%_a.length==0&&mo(_a,Es):u.length==r.sel.ranges.length&&(c=mo(u,function(t){return[t]})));for(var f=r.sel.ranges.length-1;f>=0;f--){var h=r.sel.ranges[f],d=h.from(),p=h.to();a<n.length?d=ya(d.line,d.ch-(n.length-a)):t.state.overwrite&&h.empty()&&!t.state.pasteIncoming&&(p=ya(p.line,Math.min(Ei(r,p.line).text.length,p.ch+po(u).length)));var g=t.curOp.updateInput,m={from:d,to:p,text:c?c[f%c.length]:u,origin:t.state.pasteIncoming?"paste":t.state.cutIncoming?"cut":"+input"};sr(t.doc,m);io(t,"inputRead",t,m);if(l&&!t.state.pasteIncoming&&t.options.electricChars&&t.options.smartIndent&&h.head.ch<100&&(!f||r.sel.ranges[f-1].head.line!=h.head.line)){var v=t.getModeAt(h.head),y=Ea(m);if(v.electricChars){for(var b=0;b<v.electricChars.length;b++)if(l.indexOf(v.electricChars.charAt(b))>-1){wr(t,y.line,"smart");break}}else v.electricInput&&v.electricInput.test(Ei(r,y.line).text.slice(0,y.ch))&&wr(t,y.line,"smart")}}br(t);t.curOp.updateInput=g;t.curOp.typing=!0;i.length>1e3||i.indexOf("\n")>-1?e.value=t.display.prevInput="":t.display.prevInput=i;o&&tn(t);t.state.pasteIncoming=t.state.cutIncoming=!1;return!0}function Tn(t,e){var n,r,i=t.doc;if(t.somethingSelected()){t.display.prevInput="";var o=i.sel.primary();n=Is&&(o.to().line-o.from().line>100||(r=t.getSelection()).length>1e3);var a=n?"-":r||t.getSelection();t.display.input.value=a;t.state.focused&&xs(t.display.input);Qo&&ta>=9&&(t.display.inputHasSelection=a)}else if(!e){t.display.prevInput=t.display.input.value="";Qo&&ta>=9&&(t.display.inputHasSelection=null)}t.display.inaccurateSelection=n}function kn(t){"nocursor"==t.options.readOnly||ca&&Mo()==t.display.input||t.display.input.focus()}function _n(t){if(!t.state.focused){kn(t);Zn(t)}}function Mn(t){return t.options.readOnly||t.doc.cantEdit}function Dn(t){function e(){t.state.focused&&setTimeout(bo(kn,t),0)}function n(e){ao(t,e)||ls(e)}function r(e){if(t.somethingSelected()){_a=t.getSelections();if(i.inaccurateSelection){i.prevInput="";i.inaccurateSelection=!1;i.input.value=_a.join("\n");xs(i.input)}}else{for(var n=[],r=[],o=0;o<t.doc.sel.ranges.length;o++){var a=t.doc.sel.ranges[o].head.line,s={anchor:ya(a,0),head:ya(a+1,0)};r.push(s);n.push(t.getRange(s.anchor,s.head))}if("cut"==e.type)t.setSelections(r,null,gs);else{i.prevInput="";i.input.value=n.join("\n");xs(i.input)}_a=n}"cut"==e.type&&(t.state.cutIncoming=!0)}var i=t.display;us(i.scroller,"mousedown",un(t,En));Qo&&11>ta?us(i.scroller,"dblclick",un(t,function(e){if(!ao(t,e)){var n=Nn(t,e);if(n&&!On(t,e)&&!An(t.display,e)){as(e);var r=t.findWordAt(n);re(t.doc,r.anchor,r.head)}}})):us(i.scroller,"dblclick",function(e){ao(t,e)||as(e)});us(i.lineSpace,"selectstart",function(t){An(i,t)||as(t)});ga||us(i.scroller,"contextmenu",function(e){tr(t,e)});us(i.scroller,"scroll",function(){if(i.scroller.clientHeight){Wn(t,i.scroller.scrollTop);zn(t,i.scroller.scrollLeft,!0);fs(t,"scroll",t)}});us(i.scrollbarV,"scroll",function(){i.scroller.clientHeight&&Wn(t,i.scrollbarV.scrollTop)});us(i.scrollbarH,"scroll",function(){i.scroller.clientHeight&&zn(t,i.scrollbarH.scrollLeft)});us(i.scroller,"mousewheel",function(e){qn(t,e)});us(i.scroller,"DOMMouseScroll",function(e){qn(t,e)});us(i.scrollbarH,"mousedown",e);us(i.scrollbarV,"mousedown",e);us(i.wrapper,"scroll",function(){i.wrapper.scrollTop=i.wrapper.scrollLeft=0});us(i.input,"keyup",function(e){Jn.call(t,e)});us(i.input,"input",function(){Qo&&ta>=9&&t.display.inputHasSelection&&(t.display.inputHasSelection=null);Cn(t)});us(i.input,"keydown",un(t,$n));us(i.input,"keypress",un(t,Kn));us(i.input,"focus",bo(Zn,t));us(i.input,"blur",bo(Qn,t));if(t.options.dragDrop){us(i.scroller,"dragstart",function(e){Rn(t,e)});us(i.scroller,"dragenter",n);us(i.scroller,"dragover",n);us(i.scroller,"drop",un(t,Fn))}us(i.scroller,"paste",function(e){if(!An(i,e)){t.state.pasteIncoming=!0;kn(t);Cn(t)}});us(i.input,"paste",function(){if(ea&&!t.state.fakedLastChar&&!(new Date-t.state.lastMiddleDown<200)){var e=i.input.selectionStart,n=i.input.selectionEnd;i.input.value+="$";i.input.selectionEnd=n;i.input.selectionStart=e;t.state.fakedLastChar=!0}t.state.pasteIncoming=!0;Cn(t)});us(i.input,"cut",r);us(i.input,"copy",r);aa&&us(i.sizer,"mouseup",function(){Mo()==i.input&&i.input.blur();kn(t)})}function Ln(t){var e=t.display;if(e.lastWrapHeight!=e.wrapper.clientHeight||e.lastWrapWidth!=e.wrapper.clientWidth){e.cachedCharWidth=e.cachedTextHeight=e.cachedPaddingH=null;t.setSize()}}function An(t,e){for(var n=no(e);n!=t.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==t.sizer&&n!=t.mover)return!0}function Nn(t,e,n,r){var i=t.display;if(!n){var o=no(e);if(o==i.scrollbarH||o==i.scrollbarV||o==i.scrollbarFiller||o==i.gutterFiller)return null}var a,s,l=i.lineSpace.getBoundingClientRect();try{a=e.clientX-l.left;s=e.clientY-l.top}catch(e){return null}var u,c=$e(t,a,s);if(r&&1==c.xRel&&(u=Ei(t.doc,c.line).text).length==c.ch){var f=ys(u,u.length,t.options.tabSize)-u.length;c=ya(c.line,Math.max(0,Math.round((a-Me(t.display).left)/Ke(t.display))-f))}return c}function En(t){if(!ao(this,t)){var e=this,n=e.display;n.shift=t.shiftKey;if(An(n,t)){if(!ea){n.scroller.draggable=!1;setTimeout(function(){n.scroller.draggable=!0},100)}}else if(!On(e,t)){var r=Nn(e,t);window.focus();switch(ro(t)){case 1:r?jn(e,t,r):no(t)==n.scroller&&as(t);break;case 2:ea&&(e.state.lastMiddleDown=+new Date);r&&re(e.doc,r);setTimeout(bo(kn,e),20);as(t);break;case 3:ga&&tr(e,t)}}}}function jn(t,e,n){setTimeout(bo(_n,t),0);var r,i=+new Date;if(Ca&&Ca.time>i-400&&0==ba(Ca.pos,n))r="triple";else if(wa&&wa.time>i-400&&0==ba(wa.pos,n)){r="double";Ca={time:i,pos:n}}else{r="single";wa={time:i,pos:n}}var o=t.doc.sel,a=fa?e.metaKey:e.ctrlKey;t.options.dragDrop&&Ns&&!Mn(t)&&"single"==r&&o.contains(n)>-1&&o.somethingSelected()?In(t,e,n,a):Pn(t,e,n,r,a)}function In(t,e,n,r){var i=t.display,o=un(t,function(a){ea&&(i.scroller.draggable=!1);t.state.draggingText=!1;cs(document,"mouseup",o);cs(i.scroller,"drop",o);if(Math.abs(e.clientX-a.clientX)+Math.abs(e.clientY-a.clientY)<10){as(a);r||re(t.doc,n);kn(t);Qo&&9==ta&&setTimeout(function(){document.body.focus();kn(t)},20)}});ea&&(i.scroller.draggable=!0);t.state.draggingText=o;i.scroller.dragDrop&&i.scroller.dragDrop();us(document,"mouseup",o);us(i.scroller,"drop",o)}function Pn(t,e,n,r,i){function o(e){if(0!=ba(g,e)){g=e;if("rect"==r){for(var i=[],o=t.options.tabSize,a=ys(Ei(u,n.line).text,n.ch,o),s=ys(Ei(u,e.line).text,e.ch,o),l=Math.min(a,s),d=Math.max(a,s),p=Math.min(n.line,e.line),m=Math.min(t.lastLine(),Math.max(n.line,e.line));m>=p;p++){var v=Ei(u,p).text,y=fo(v,l,o);l==d?i.push(new $(ya(p,y),ya(p,y))):v.length>y&&i.push(new $(ya(p,y),ya(p,fo(v,d,o))))}i.length||i.push(new $(n,n));ue(u,Y(h.ranges.slice(0,f).concat(i),f),{origin:"*mouse",scroll:!1});t.scrollIntoView(e)}else{var b=c,x=b.anchor,w=e;if("single"!=r){if("double"==r)var C=t.findWordAt(e);else var C=new $(ya(e.line,0),Z(u,ya(e.line+1,0)));if(ba(C.anchor,x)>0){w=C.head;x=X(b.from(),C.anchor)}else{w=C.anchor;x=V(b.to(),C.head)}}var i=h.ranges.slice(0);i[f]=new $(Z(u,x),w);ue(u,Y(i,f),ms)}}}function a(e){var n=++y,i=Nn(t,e,!0,"rect"==r);if(i)if(0!=ba(i,g)){_n(t);o(i);var s=v(l,u);(i.line>=s.to||i.line<s.from)&&setTimeout(un(t,function(){y==n&&a(e)}),150)}else{var c=e.clientY<m.top?-20:e.clientY>m.bottom?20:0;c&&setTimeout(un(t,function(){if(y==n){l.scroller.scrollTop+=c;a(e)}}),50)}}function s(e){y=1/0;as(e);kn(t);cs(document,"mousemove",b);cs(document,"mouseup",x);u.history.lastSelOrigin=null}var l=t.display,u=t.doc;as(e);var c,f,h=u.sel;if(i&&!e.shiftKey){f=u.sel.contains(n);c=f>-1?u.sel.ranges[f]:new $(n,n)}else c=u.sel.primary();if(e.altKey){r="rect";i||(c=new $(n,n));n=Nn(t,e,!0,!0);f=-1}else if("double"==r){var d=t.findWordAt(n);c=t.display.shift||u.extend?ne(u,c,d.anchor,d.head):d}else if("triple"==r){var p=new $(ya(n.line,0),Z(u,ya(n.line+1,0)));c=t.display.shift||u.extend?ne(u,c,p.anchor,p.head):p}else c=ne(u,c,n);if(i)if(f>-1)oe(u,f,c,ms);else{f=u.sel.ranges.length;ue(u,Y(u.sel.ranges.concat([c]),f),{scroll:!1,origin:"*mouse"})}else{f=0;ue(u,new G([c],0),ms);h=u.sel}var g=n,m=l.wrapper.getBoundingClientRect(),y=0,b=un(t,function(t){ro(t)?a(t):s(t)}),x=un(t,s);us(document,"mousemove",b);us(document,"mouseup",x)}function Hn(t,e,n,r,i){try{var o=e.clientX,a=e.clientY}catch(e){return!1}if(o>=Math.floor(t.display.gutters.getBoundingClientRect().right))return!1;r&&as(e);var s=t.display,l=s.lineDiv.getBoundingClientRect();if(a>l.bottom||!lo(t,n))return eo(e);a-=l.top-s.viewOffset;for(var u=0;u<t.options.gutters.length;++u){var c=s.gutters.childNodes[u];if(c&&c.getBoundingClientRect().right>=o){var f=Oi(t.doc,a),h=t.options.gutters[u];i(t,n,t,f,h,e);return eo(e)}}}function On(t,e){return Hn(t,e,"gutterClick",!0,io)}function Fn(t){var e=this;if(!ao(e,t)&&!An(e.display,t)){as(t);Qo&&(Ma=+new Date);var n=Nn(e,t,!0),r=t.dataTransfer.files;if(n&&!Mn(e))if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),a=0,s=function(t,r){var s=new FileReader;s.onload=un(e,function(){o[r]=s.result;if(++a==i){n=Z(e.doc,n);var t={from:n,to:n,text:Es(o.join("\n")),origin:"paste"};sr(e.doc,t);le(e.doc,J(n,Ea(t)))}});s.readAsText(t)},l=0;i>l;++l)s(r[l],l);else{if(e.state.draggingText&&e.doc.sel.contains(n)>-1){e.state.draggingText(t);setTimeout(bo(kn,e),20);return}try{var o=t.dataTransfer.getData("Text");if(o){if(e.state.draggingText&&!(fa?t.metaKey:t.ctrlKey))var u=e.listSelections();ce(e.doc,J(n,n));if(u)for(var l=0;l<u.length;++l)dr(e.doc,"",u[l].anchor,u[l].head,"drag");e.replaceSelection(o,"around","paste");kn(e)}}catch(t){}}}}function Rn(t,e){if(Qo&&(!t.state.draggingText||+new Date-Ma<100))ls(e);else if(!ao(t,e)&&!An(t.display,e)){e.dataTransfer.setData("Text",t.getSelection());if(e.dataTransfer.setDragImage&&!oa){var n=So("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(ia){n.width=n.height=1;t.display.wrapper.appendChild(n);n._top=n.offsetTop}e.dataTransfer.setDragImage(n,0,0);ia&&n.parentNode.removeChild(n)}}}function Wn(t,e){if(!(Math.abs(t.doc.scrollTop-e)<2)){t.doc.scrollTop=e;Jo||k(t,{top:e});t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e);t.display.scrollbarV.scrollTop!=e&&(t.display.scrollbarV.scrollTop=e);Jo&&k(t);we(t,100)}}function zn(t,e,n){if(!(n?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)){e=Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth);t.doc.scrollLeft=e;y(t);t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e);t.display.scrollbarH.scrollLeft!=e&&(t.display.scrollbarH.scrollLeft=e)}}function qn(t,e){var n=e.wheelDeltaX,r=e.wheelDeltaY;null==n&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(n=e.detail);null==r&&e.detail&&e.axis==e.VERTICAL_AXIS?r=e.detail:null==r&&(r=e.wheelDelta);var i=t.display,o=i.scroller;if(n&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&fa&&ea)t:for(var a=e.target,s=i.view;a!=o;a=a.parentNode)for(var l=0;l<s.length;l++)if(s[l].node==a){t.display.currentWheelTarget=a;break t}if(!n||Jo||ia||null==La){if(r&&null!=La){var u=r*La,c=t.doc.scrollTop,f=c+i.wrapper.clientHeight;0>u?c=Math.max(0,c+u-50):f=Math.min(t.doc.height,f+u+50);k(t,{top:c,bottom:f})}if(20>Da)if(null==i.wheelStartX){i.wheelStartX=o.scrollLeft;i.wheelStartY=o.scrollTop;i.wheelDX=n;i.wheelDY=r;setTimeout(function(){if(null!=i.wheelStartX){var t=o.scrollLeft-i.wheelStartX,e=o.scrollTop-i.wheelStartY,n=e&&i.wheelDY&&e/i.wheelDY||t&&i.wheelDX&&t/i.wheelDX;i.wheelStartX=i.wheelStartY=null;if(n){La=(La*Da+n)/(Da+1);++Da}}},200)}else{i.wheelDX+=n;i.wheelDY+=r}}else{r&&Wn(t,Math.max(0,Math.min(o.scrollTop+r*La,o.scrollHeight-o.clientHeight)));zn(t,Math.max(0,Math.min(o.scrollLeft+n*La,o.scrollWidth-o.clientWidth)));as(e);i.wheelStartX=null}}}function Un(t,e,n){if("string"==typeof e){e=Ua[e];if(!e)return!1}t.display.pollingFast&&Sn(t)&&(t.display.pollingFast=!1);var r=t.display.shift,i=!1;try{Mn(t)&&(t.state.suppressEdits=!0);n&&(t.display.shift=!1);i=e(t)!=ps}finally{t.display.shift=r;t.state.suppressEdits=!1}return i}function Bn(t,e,n){for(var r=0;r<t.state.keyMaps.length;r++){var i=Va(e,t.state.keyMaps[r],n);if(i)return i}return t.options.extraKeys&&Va(e,t.options.extraKeys,n)||Va(e,t.options.keyMap,n)}function Vn(t,e,n,r){var i=t.state.keySeq;if(i){if(Xa(e))return"handled";Aa.set(50,function(){if(t.state.keySeq==i){t.state.keySeq=null;Tn(t)}});e=i+" "+e}var o=Bn(t,e,r);"multi"==o&&(t.state.keySeq=e);"handled"==o&&io(t,"keyHandled",t,e,n);if("handled"==o||"multi"==o){as(n);xe(t)}if(i&&!o&&/\'$/.test(e)){as(n);return!0}return!!o}function Xn(t,e){var n=Ga(e,!0);return n?e.shiftKey&&!t.state.keySeq?Vn(t,"Shift-"+n,e,function(e){return Un(t,e,!0)})||Vn(t,n,e,function(e){return("string"==typeof e?/^go[A-Z]/.test(e):e.motion)?Un(t,e):void 0}):Vn(t,n,e,function(e){return Un(t,e)}):!1}function Gn(t,e,n){return Vn(t,"'"+n+"'",e,function(e){return Un(t,e,!0)})}function $n(t){var e=this;_n(e);if(!ao(e,t)){Qo&&11>ta&&27==t.keyCode&&(t.returnValue=!1);var n=t.keyCode;e.display.shift=16==n||t.shiftKey;var r=Xn(e,t);if(ia){Na=r?n:null;!r&&88==n&&!Is&&(fa?t.metaKey:t.ctrlKey)&&e.replaceSelection("",null,"cut")}18!=n||/\bCodeMirror-crosshair\b/.test(e.display.lineDiv.className)||Yn(e)}}function Yn(t){function e(t){if(18==t.keyCode||!t.altKey){Ds(n,"CodeMirror-crosshair");cs(document,"keyup",e);cs(document,"mouseover",e)}}var n=t.display.lineDiv;Ls(n,"CodeMirror-crosshair");us(document,"keyup",e);us(document,"mouseover",e)}function Jn(t){16==t.keyCode&&(this.doc.sel.shift=!1);ao(this,t)}function Kn(t){var e=this;if(!(ao(e,t)||t.ctrlKey&&!t.altKey||fa&&t.metaKey)){var n=t.keyCode,r=t.charCode;if(ia&&n==Na){Na=null;as(t)}else if(!(ia&&(!t.which||t.which<10)||aa)||!Xn(e,t)){var i=String.fromCharCode(null==r?n:r);if(!Gn(e,t,i)){Qo&&ta>=9&&(e.display.inputHasSelection=null);Cn(e)}}}}function Zn(t){if("nocursor"!=t.options.readOnly){if(!t.state.focused){fs(t,"focus",t);t.state.focused=!0;Ls(t.display.wrapper,"CodeMirror-focused");if(!t.curOp&&t.display.selForContextMenu!=t.doc.sel){Tn(t);ea&&setTimeout(bo(Tn,t,!0),0)}}wn(t);xe(t)}}function Qn(t){if(t.state.focused){fs(t,"blur",t);t.state.focused=!1;Ds(t.display.wrapper,"CodeMirror-focused")}clearInterval(t.display.blinker);setTimeout(function(){t.state.focused||(t.display.shift=!1)},150)}function tr(t,e){function n(){if(null!=i.input.selectionStart){var e=t.somethingSelected(),n=i.input.value="​"+(e?i.input.value:"");i.prevInput=e?"":"​";i.input.selectionStart=1;i.input.selectionEnd=n.length;i.selForContextMenu=t.doc.sel}}function r(){i.inputDiv.style.position="relative";i.input.style.cssText=l;Qo&&9>ta&&(i.scrollbarV.scrollTop=i.scroller.scrollTop=a);wn(t);if(null!=i.input.selectionStart){(!Qo||Qo&&9>ta)&&n();var e=0,r=function(){i.selForContextMenu==t.doc.sel&&0==i.input.selectionStart?un(t,Ua.selectAll)(t):e++<10?i.detectingSelectAll=setTimeout(r,500):Tn(t)};i.detectingSelectAll=setTimeout(r,200)}}if(!ao(t,e,"contextmenu")){var i=t.display;if(!An(i,e)&&!er(t,e)){var o=Nn(t,e),a=i.scroller.scrollTop;if(o&&!ia){var s=t.options.resetSelectionOnContextMenu;s&&-1==t.doc.sel.contains(o)&&un(t,ue)(t.doc,J(o),gs);var l=i.input.style.cssText;i.inputDiv.style.position="absolute";i.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(e.clientY-5)+"px; left: "+(e.clientX-5)+"px; z-index: 1000; background: "+(Qo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ea)var u=window.scrollY;kn(t);ea&&window.scrollTo(null,u);Tn(t);t.somethingSelected()||(i.input.value=i.prevInput=" ");i.selForContextMenu=t.doc.sel;clearTimeout(i.detectingSelectAll);Qo&&ta>=9&&n();if(ga){ls(e);var c=function(){cs(window,"mouseup",c);setTimeout(r,20)};us(window,"mouseup",c)}else setTimeout(r,50)}}}}function er(t,e){return lo(t,"gutterContextMenu")?Hn(t,e,"gutterContextMenu",!1,fs):!1}function nr(t,e){if(ba(t,e.from)<0)return t;if(ba(t,e.to)<=0)return Ea(e);var n=t.line+e.text.length-(e.to.line-e.from.line)-1,r=t.ch;t.line==e.to.line&&(r+=Ea(e).ch-e.to.ch);return ya(n,r)}function rr(t,e){for(var n=[],r=0;r<t.sel.ranges.length;r++){var i=t.sel.ranges[r];n.push(new $(nr(i.anchor,e),nr(i.head,e)))}return Y(n,t.sel.primIndex)}function ir(t,e,n){return t.line==e.line?ya(n.line,t.ch-e.ch+n.ch):ya(n.line+(t.line-e.line),t.ch)}function or(t,e,n){for(var r=[],i=ya(t.first,0),o=i,a=0;a<e.length;a++){var s=e[a],l=ir(s.from,i,o),u=ir(Ea(s),i,o);i=s.to;o=u;if("around"==n){var c=t.sel.ranges[a],f=ba(c.head,c.anchor)<0;r[a]=new $(f?u:l,f?l:u)}else r[a]=new $(l,l)}return new G(r,t.sel.primIndex)}function ar(t,e,n){var r={canceled:!1,from:e.from,to:e.to,text:e.text,origin:e.origin,cancel:function(){this.canceled=!0}};n&&(r.update=function(e,n,r,i){e&&(this.from=Z(t,e));n&&(this.to=Z(t,n));r&&(this.text=r);void 0!==i&&(this.origin=i)});fs(t,"beforeChange",t,r);t.cm&&fs(t.cm,"beforeChange",t.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function sr(t,e,n){if(t.cm){if(!t.cm.curOp)return un(t.cm,sr)(t,e,n);if(t.cm.state.suppressEdits)return}if(lo(t,"beforeChange")||t.cm&&lo(t.cm,"beforeChange")){e=ar(t,e,!0);if(!e)return}var r=ma&&!n&&Ur(t,e.from,e.to);if(r)for(var i=r.length-1;i>=0;--i)lr(t,{from:r[i].from,to:r[i].to,text:i?[""]:e.text});else lr(t,e)}function lr(t,e){if(1!=e.text.length||""!=e.text[0]||0!=ba(e.from,e.to)){var n=rr(t,e);Bi(t,e,n,t.cm?t.cm.curOp.id:0/0);fr(t,e,n,Wr(t,e));var r=[];Ai(t,function(t,n){if(!n&&-1==go(r,t.history)){to(t.history,e);r.push(t.history)}fr(t,e,null,Wr(t,e))})}}function ur(t,e,n){if(!t.cm||!t.cm.state.suppressEdits){for(var r,i=t.history,o=t.sel,a="undo"==e?i.done:i.undone,s="undo"==e?i.undone:i.done,l=0;l<a.length;l++){r=a[l];if(n?r.ranges&&!r.equals(t.sel):!r.ranges)break}if(l!=a.length){i.lastOrigin=i.lastSelOrigin=null;for(;;){r=a.pop();if(!r.ranges)break;Gi(r,s);if(n&&!r.equals(t.sel)){ue(t,r,{clearRedo:!1});return}o=r}var u=[];Gi(o,s);s.push({changes:u,generation:i.generation});i.generation=r.generation||++i.maxGeneration;for(var c=lo(t,"beforeChange")||t.cm&&lo(t.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var f=r.changes[l];f.origin=e;if(c&&!ar(t,f,!1)){a.length=0;return}u.push(zi(t,f));var h=l?rr(t,f):po(a);fr(t,f,h,qr(t,f));!l&&t.cm&&t.cm.scrollIntoView({from:f.from,to:Ea(f)});var d=[];Ai(t,function(t,e){if(!e&&-1==go(d,t.history)){to(t.history,f);d.push(t.history)}fr(t,f,null,qr(t,f))})}}}}function cr(t,e){if(0!=e){t.first+=e;t.sel=new G(mo(t.sel.ranges,function(t){return new $(ya(t.anchor.line+e,t.anchor.ch),ya(t.head.line+e,t.head.ch))}),t.sel.primIndex);if(t.cm){pn(t.cm,t.first,t.first-e,e);for(var n=t.cm.display,r=n.viewFrom;r<n.viewTo;r++)gn(t.cm,r,"gutter")}}}function fr(t,e,n,r){if(t.cm&&!t.cm.curOp)return un(t.cm,fr)(t,e,n,r);if(e.to.line<t.first)cr(t,e.text.length-1-(e.to.line-e.from.line));else if(!(e.from.line>t.lastLine())){if(e.from.line<t.first){var i=e.text.length-1-(t.first-e.from.line);cr(t,i);e={from:ya(t.first,0),to:ya(e.to.line+i,e.to.ch),text:[po(e.text)],origin:e.origin}}var o=t.lastLine(); e.to.line>o&&(e={from:e.from,to:ya(o,Ei(t,o).text.length),text:[e.text[0]],origin:e.origin});e.removed=ji(t,e.from,e.to);n||(n=rr(t,e));t.cm?hr(t.cm,e,r):Mi(t,e,r);ce(t,n,gs)}}function hr(t,e,n){var r=t.doc,i=t.display,a=e.from,s=e.to,l=!1,u=a.line;if(!t.options.lineWrapping){u=Hi(Qr(Ei(r,a.line)));r.iter(u,s.line+1,function(t){if(t==i.maxLine){l=!0;return!0}})}r.sel.contains(e.from,e.to)>-1&&so(t);Mi(r,e,n,o(t));if(!t.options.lineWrapping){r.iter(u,a.line+e.text.length,function(t){var e=f(t);if(e>i.maxLineLength){i.maxLine=t;i.maxLineLength=e;i.maxLineChanged=!0;l=!1}});l&&(t.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,a.line);we(t,400);var c=e.text.length-(s.line-a.line)-1;a.line!=s.line||1!=e.text.length||_i(t.doc,e)?pn(t,a.line,s.line+1,c):gn(t,a.line,"text");var h=lo(t,"changes"),d=lo(t,"change");if(d||h){var p={from:a,to:s,text:e.text,removed:e.removed,origin:e.origin};d&&io(t,"change",t,p);h&&(t.curOp.changeObjs||(t.curOp.changeObjs=[])).push(p)}t.display.selForContextMenu=null}function dr(t,e,n,r,i){r||(r=n);if(ba(r,n)<0){var o=r;r=n;n=o}"string"==typeof e&&(e=Es(e));sr(t,{from:n,to:r,text:e,origin:i})}function pr(t,e){if(!ao(t,"scrollCursorIntoView")){var n=t.display,r=n.sizer.getBoundingClientRect(),i=null;e.top+r.top<0?i=!0:e.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1);if(null!=i&&!la){var o=So("div","​",null,"position: absolute; top: "+(e.top-n.viewOffset-ke(t.display))+"px; height: "+(e.bottom-e.top+ds)+"px; left: "+e.left+"px; width: 2px;");t.display.lineSpace.appendChild(o);o.scrollIntoView(i);t.display.lineSpace.removeChild(o)}}}function gr(t,e,n,r){null==r&&(r=0);for(var i=0;5>i;i++){var o=!1,a=Ve(t,e),s=n&&n!=e?Ve(t,n):a,l=vr(t,Math.min(a.left,s.left),Math.min(a.top,s.top)-r,Math.max(a.left,s.left),Math.max(a.bottom,s.bottom)+r),u=t.doc.scrollTop,c=t.doc.scrollLeft;if(null!=l.scrollTop){Wn(t,l.scrollTop);Math.abs(t.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zn(t,l.scrollLeft);Math.abs(t.doc.scrollLeft-c)>1&&(o=!0)}if(!o)return a}}function mr(t,e,n,r,i){var o=vr(t,e,n,r,i);null!=o.scrollTop&&Wn(t,o.scrollTop);null!=o.scrollLeft&&zn(t,o.scrollLeft)}function vr(t,e,n,r,i){var o=t.display,a=Je(t.display);0>n&&(n=0);var s=t.curOp&&null!=t.curOp.scrollTop?t.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-ds,u={};i-n>l&&(i=n+l);var c=t.doc.height+_e(o),f=a>n,h=i>c-a;if(s>n)u.scrollTop=f?0:n;else if(i>s+l){var d=Math.min(n,(h?c:i)-l);d!=s&&(u.scrollTop=d)}var p=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:o.scroller.scrollLeft,g=o.scroller.clientWidth-ds-o.gutters.offsetWidth,m=r-e>g;m&&(r=e+g);10>e?u.scrollLeft=0:p>e?u.scrollLeft=Math.max(0,e-(m?0:10)):r>g+p-3&&(u.scrollLeft=r+(m?0:10)-g);return u}function yr(t,e,n){(null!=e||null!=n)&&xr(t);null!=e&&(t.curOp.scrollLeft=(null==t.curOp.scrollLeft?t.doc.scrollLeft:t.curOp.scrollLeft)+e);null!=n&&(t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+n)}function br(t){xr(t);var e=t.getCursor(),n=e,r=e;if(!t.options.lineWrapping){n=e.ch?ya(e.line,e.ch-1):e;r=ya(e.line,e.ch+1)}t.curOp.scrollToPos={from:n,to:r,margin:t.options.cursorScrollMargin,isCursor:!0}}function xr(t){var e=t.curOp.scrollToPos;if(e){t.curOp.scrollToPos=null;var n=Xe(t,e.from),r=Xe(t,e.to),i=vr(t,Math.min(n.left,r.left),Math.min(n.top,r.top)-e.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+e.margin);t.scrollTo(i.scrollLeft,i.scrollTop)}}function wr(t,e,n,r){var i,o=t.doc;null==n&&(n="add");"smart"==n&&(o.mode.indent?i=Te(t,e):n="prev");var a=t.options.tabSize,s=Ei(o,e),l=ys(s.text,null,a);s.stateAfter&&(s.stateAfter=null);var u,c=s.text.match(/^\s*/)[0];if(r||/\S/.test(s.text)){if("smart"==n){u=o.mode.indent(i,s.text.slice(c.length),s.text);if(u==ps||u>150){if(!r)return;n="prev"}}}else{u=0;n="not"}"prev"==n?u=e>o.first?ys(Ei(o,e-1).text,null,a):0:"add"==n?u=l+t.options.indentUnit:"subtract"==n?u=l-t.options.indentUnit:"number"==typeof n&&(u=l+n);u=Math.max(0,u);var f="",h=0;if(t.options.indentWithTabs)for(var d=Math.floor(u/a);d;--d){h+=a;f+=" "}u>h&&(f+=ho(u-h));if(f!=c)dr(o,f,ya(e,0),ya(e,c.length),"+input");else for(var d=0;d<o.sel.ranges.length;d++){var p=o.sel.ranges[d];if(p.head.line==e&&p.head.ch<c.length){var h=ya(e,c.length);oe(o,d,new $(h,h));break}}s.stateAfter=null}function Cr(t,e,n,r){var i=e,o=e;"number"==typeof e?o=Ei(t,K(t,e)):i=Hi(e);if(null==i)return null;r(o,i)&&t.cm&&gn(t.cm,i,n);return o}function Sr(t,e){for(var n=t.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=e(n[i]);r.length&&ba(o.from,po(r).to)<=0;){var a=r.pop();if(ba(a.from,o.from)<0){o.from=a.from;break}}r.push(o)}ln(t,function(){for(var e=r.length-1;e>=0;e--)dr(t.doc,"",r[e].from,r[e].to,"+delete");br(t)})}function Tr(t,e,n,r,i){function o(){var e=s+n;if(e<t.first||e>=t.first+t.size)return f=!1;s=e;return c=Ei(t,e)}function a(t){var e=(i?$o:Yo)(c,l,n,!0);if(null==e){if(t||!o())return f=!1;l=i?(0>n?zo:Wo)(c):0>n?c.text.length:0}else l=e;return!0}var s=e.line,l=e.ch,u=n,c=Ei(t,s),f=!0;if("char"==r)a();else if("column"==r)a(!0);else if("word"==r||"group"==r)for(var h=null,d="group"==r,p=t.cm&&t.cm.getHelper(e,"wordChars"),g=!0;!(0>n)||a(!g);g=!1){var m=c.text.charAt(l)||"\n",v=xo(m,p)?"w":d&&"\n"==m?"n":!d||/\s/.test(m)?null:"p";!d||g||v||(v="s");if(h&&h!=v){if(0>n){n=1;a()}break}v&&(h=v);if(n>0&&!a(!g))break}var y=pe(t,ya(s,l),u,!0);f||(y.hitSide=!0);return y}function kr(t,e,n,r){var i,o=t.doc,a=e.left;if("page"==r){var s=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);i=e.top+n*(s-(0>n?1.5:.5)*Je(t.display))}else"line"==r&&(i=n>0?e.bottom+3:e.top-3);for(;;){var l=$e(t,a,i);if(!l.outside)break;if(0>n?0>=i:i>=o.height){l.hitSide=!0;break}i+=5*n}return l}function _r(e,n,r,i){t.defaults[e]=n;r&&(Ia[e]=i?function(t,e,n){n!=Pa&&r(t,e,n)}:r)}function Mr(t){for(var e,n,r,i,o=t.split(/-(?!$)/),t=o[o.length-1],a=0;a<o.length-1;a++){var s=o[a];if(/^(cmd|meta|m)$/i.test(s))i=!0;else if(/^a(lt)?$/i.test(s))e=!0;else if(/^(c|ctrl|control)$/i.test(s))n=!0;else{if(!/^s(hift)$/i.test(s))throw new Error("Unrecognized modifier name: "+s);r=!0}}e&&(t="Alt-"+t);n&&(t="Ctrl-"+t);i&&(t="Cmd-"+t);r&&(t="Shift-"+t);return t}function Dr(t){return"string"==typeof t?Ba[t]:t}function Lr(t,e,n,r,i){if(r&&r.shared)return Ar(t,e,n,r,i);if(t.cm&&!t.cm.curOp)return un(t.cm,Lr)(t,e,n,r,i);var o=new Ya(t,i),a=ba(e,n);r&&yo(r,o,!1);if(a>0||0==a&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=So("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0);r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(Zr(t,e.line,e,n,o)||e.line!=n.line&&Zr(t,n.line,e,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");va=!0}o.addToHistory&&Bi(t,{from:e,to:n,origin:"markText"},t.sel,0/0);var s,l=e.line,u=t.cm;t.iter(l,n.line+1,function(t){u&&o.collapsed&&!u.options.lineWrapping&&Qr(t)==u.display.maxLine&&(s=!0);o.collapsed&&l!=e.line&&Pi(t,0);Or(t,new Ir(o,l==e.line?e.ch:null,l==n.line?n.ch:null));++l});o.collapsed&&t.iter(e.line,n.line+1,function(e){ri(t,e)&&Pi(e,0)});o.clearOnEnter&&us(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){ma=!0;(t.history.done.length||t.history.undone.length)&&t.clearHistory()}if(o.collapsed){o.id=++Ja;o.atomic=!0}if(u){s&&(u.curOp.updateMaxLine=!0);if(o.collapsed)pn(u,e.line,n.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var c=e.line;c<=n.line;c++)gn(u,c,"text");o.atomic&&he(u.doc);io(u,"markerAdded",u,o)}return o}function Ar(t,e,n,r,i){r=yo(r);r.shared=!1;var o=[Lr(t,e,n,r,i)],a=o[0],s=r.widgetNode;Ai(t,function(t){s&&(r.widgetNode=s.cloneNode(!0));o.push(Lr(t,Z(t,e),Z(t,n),r,i));for(var l=0;l<t.linked.length;++l)if(t.linked[l].isParent)return;a=po(o)});return new Ka(o,a)}function Nr(t){return t.findMarks(ya(t.first,0),t.clipPos(ya(t.lastLine())),function(t){return t.parent})}function Er(t,e){for(var n=0;n<e.length;n++){var r=e[n],i=r.find(),o=t.clipPos(i.from),a=t.clipPos(i.to);if(ba(o,a)){var s=Lr(t,o,a,r.primary,r.primary.type);r.markers.push(s);s.parent=r}}}function jr(t){for(var e=0;e<t.length;e++){var n=t[e],r=[n.primary.doc];Ai(n.primary.doc,function(t){r.push(t)});for(var i=0;i<n.markers.length;i++){var o=n.markers[i];if(-1==go(r,o.doc)){o.parent=null;n.markers.splice(i--,1)}}}}function Ir(t,e,n){this.marker=t;this.from=e;this.to=n}function Pr(t,e){if(t)for(var n=0;n<t.length;++n){var r=t[n];if(r.marker==e)return r}}function Hr(t,e){for(var n,r=0;r<t.length;++r)t[r]!=e&&(n||(n=[])).push(t[r]);return n}function Or(t,e){t.markedSpans=t.markedSpans?t.markedSpans.concat([e]):[e];e.marker.attachLine(t)}function Fr(t,e,n){if(t)for(var r,i=0;i<t.length;++i){var o=t[i],a=o.marker,s=null==o.from||(a.inclusiveLeft?o.from<=e:o.from<e);if(s||o.from==e&&"bookmark"==a.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(a.inclusiveRight?o.to>=e:o.to>e);(r||(r=[])).push(new Ir(a,o.from,l?null:o.to))}}return r}function Rr(t,e,n){if(t)for(var r,i=0;i<t.length;++i){var o=t[i],a=o.marker,s=null==o.to||(a.inclusiveRight?o.to>=e:o.to>e);if(s||o.from==e&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=e:o.from<e);(r||(r=[])).push(new Ir(a,l?null:o.from-e,null==o.to?null:o.to-e))}}return r}function Wr(t,e){var n=te(t,e.from.line)&&Ei(t,e.from.line).markedSpans,r=te(t,e.to.line)&&Ei(t,e.to.line).markedSpans;if(!n&&!r)return null;var i=e.from.ch,o=e.to.ch,a=0==ba(e.from,e.to),s=Fr(n,i,a),l=Rr(r,o,a),u=1==e.text.length,c=po(e.text).length+(u?i:0);if(s)for(var f=0;f<s.length;++f){var h=s[f];if(null==h.to){var d=Pr(l,h.marker);d?u&&(h.to=null==d.to?null:d.to+c):h.to=i}}if(l)for(var f=0;f<l.length;++f){var h=l[f];null!=h.to&&(h.to+=c);if(null==h.from){var d=Pr(s,h.marker);if(!d){h.from=c;u&&(s||(s=[])).push(h)}}else{h.from+=c;u&&(s||(s=[])).push(h)}}s&&(s=zr(s));l&&l!=s&&(l=zr(l));var p=[s];if(!u){var g,m=e.text.length-2;if(m>0&&s)for(var f=0;f<s.length;++f)null==s[f].to&&(g||(g=[])).push(new Ir(s[f].marker,null,null));for(var f=0;m>f;++f)p.push(g);p.push(l)}return p}function zr(t){for(var e=0;e<t.length;++e){var n=t[e];null!=n.from&&n.from==n.to&&n.marker.clearWhenEmpty!==!1&&t.splice(e--,1)}return t.length?t:null}function qr(t,e){var n=Ji(t,e),r=Wr(t,e);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],a=r[i];if(o&&a)t:for(var s=0;s<a.length;++s){for(var l=a[s],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue t;o.push(l)}else a&&(n[i]=a)}return n}function Ur(t,e,n){var r=null;t.iter(e.line,n.line+1,function(t){if(t.markedSpans)for(var e=0;e<t.markedSpans.length;++e){var n=t.markedSpans[e].marker;!n.readOnly||r&&-1!=go(r,n)||(r||(r=[])).push(n)}});if(!r)return null;for(var i=[{from:e,to:n}],o=0;o<r.length;++o)for(var a=r[o],s=a.find(0),l=0;l<i.length;++l){var u=i[l];if(!(ba(u.to,s.from)<0||ba(u.from,s.to)>0)){var c=[l,1],f=ba(u.from,s.from),h=ba(u.to,s.to);(0>f||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from});(h>0||!a.inclusiveRight&&!h)&&c.push({from:s.to,to:u.to});i.splice.apply(i,c);l+=c.length-1}}return i}function Br(t){var e=t.markedSpans;if(e){for(var n=0;n<e.length;++n)e[n].marker.detachLine(t);t.markedSpans=null}}function Vr(t,e){if(e){for(var n=0;n<e.length;++n)e[n].marker.attachLine(t);t.markedSpans=e}}function Xr(t){return t.inclusiveLeft?-1:0}function Gr(t){return t.inclusiveRight?1:0}function $r(t,e){var n=t.lines.length-e.lines.length;if(0!=n)return n;var r=t.find(),i=e.find(),o=ba(r.from,i.from)||Xr(t)-Xr(e);if(o)return-o;var a=ba(r.to,i.to)||Gr(t)-Gr(e);return a?a:e.id-t.id}function Yr(t,e){var n,r=va&&t.markedSpans;if(r)for(var i,o=0;o<r.length;++o){i=r[o];i.marker.collapsed&&null==(e?i.from:i.to)&&(!n||$r(n,i.marker)<0)&&(n=i.marker)}return n}function Jr(t){return Yr(t,!0)}function Kr(t){return Yr(t,!1)}function Zr(t,e,n,r,i){var o=Ei(t,e),a=va&&o.markedSpans;if(a)for(var s=0;s<a.length;++s){var l=a[s];if(l.marker.collapsed){var u=l.marker.find(0),c=ba(u.from,n)||Xr(l.marker)-Xr(i),f=ba(u.to,r)||Gr(l.marker)-Gr(i);if(!(c>=0&&0>=f||0>=c&&f>=0)&&(0>=c&&(ba(u.to,n)>0||l.marker.inclusiveRight&&i.inclusiveLeft)||c>=0&&(ba(u.from,r)<0||l.marker.inclusiveLeft&&i.inclusiveRight)))return!0}}}function Qr(t){for(var e;e=Jr(t);)t=e.find(-1,!0).line;return t}function ti(t){for(var e,n;e=Kr(t);){t=e.find(1,!0).line;(n||(n=[])).push(t)}return n}function ei(t,e){var n=Ei(t,e),r=Qr(n);return n==r?e:Hi(r)}function ni(t,e){if(e>t.lastLine())return e;var n,r=Ei(t,e);if(!ri(t,r))return e;for(;n=Kr(r);)r=n.find(1,!0).line;return Hi(r)+1}function ri(t,e){var n=va&&e.markedSpans;if(n)for(var r,i=0;i<n.length;++i){r=n[i];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&ii(t,e,r))return!0}}}function ii(t,e,n){if(null==n.to){var r=n.marker.find(1,!0);return ii(t,r.line,Pr(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==e.text.length)return!0;for(var i,o=0;o<e.markedSpans.length;++o){i=e.markedSpans[o];if(i.marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&ii(t,e,i))return!0}}function oi(t,e,n){Fi(e)<(t.curOp&&t.curOp.scrollTop||t.doc.scrollTop)&&yr(t,null,n)}function ai(t){if(null!=t.height)return t.height;if(!_o(document.body,t.node)){var e="position: relative;";t.coverGutter&&(e+="margin-left: -"+t.cm.getGutterElement().offsetWidth+"px;");ko(t.cm.display.measure,So("div",[t.node],null,e))}return t.height=t.node.offsetHeight}function si(t,e,n,r){var i=new Za(t,n,r);i.noHScroll&&(t.display.alignWidgets=!0);Cr(t.doc,e,"widget",function(e){var n=e.widgets||(e.widgets=[]);null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i);i.line=e;if(!ri(t.doc,e)){var r=Fi(e)<t.doc.scrollTop;Pi(e,e.height+ai(i));r&&yr(t,null,i.height);t.curOp.forceUpdate=!0}return!0});return i}function li(t,e,n,r){t.text=e;t.stateAfter&&(t.stateAfter=null);t.styles&&(t.styles=null);null!=t.order&&(t.order=null);Br(t);Vr(t,n);var i=r?r(t):1;i!=t.height&&Pi(t,i)}function ui(t){t.parent=null;Br(t)}function ci(t,e){if(t)for(;;){var n=t.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;t=t.slice(0,n.index)+t.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==e[r]?e[r]=n[2]:new RegExp("(?:^|s)"+n[2]+"(?:$|s)").test(e[r])||(e[r]+=" "+n[2])}return t}function fi(e,n){if(e.blankLine)return e.blankLine(n);if(e.innerMode){var r=t.innerMode(e,n);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function hi(e,n,r,i){for(var o=0;10>o;o++){i&&(i[0]=t.innerMode(e,r).mode);var a=e.token(n,r);if(n.pos>n.start)return a}throw new Error("Mode "+e.name+" failed to advance stream.")}function di(t,e,n,r){function i(t){return{start:f.start,end:f.pos,string:f.current(),type:o||null,state:t?za(a.mode,c):c}}var o,a=t.doc,s=a.mode;e=Z(a,e);var l,u=Ei(a,e.line),c=Te(t,e.line,n),f=new $a(u.text,t.options.tabSize);r&&(l=[]);for(;(r||f.pos<e.ch)&&!f.eol();){f.start=f.pos;o=hi(s,f,c);r&&l.push(i(!0))}return r?l:i()}function pi(t,e,n,r,i,o,a){var s=n.flattenSpans;null==s&&(s=t.options.flattenSpans);var l,u=0,c=null,f=new $a(e,t.options.tabSize),h=t.options.addModeClass&&[null];""==e&&ci(fi(n,r),o);for(;!f.eol();){if(f.pos>t.options.maxHighlightLength){s=!1;a&&vi(t,e,r,f.pos);f.pos=e.length;l=null}else l=ci(hi(n,f,r,h),o);if(h){var d=h[0].name;d&&(l="m-"+(l?d+" "+l:d))}if(!s||c!=l){u<f.start&&i(f.start,c);u=f.start;c=l}f.start=f.pos}for(;u<f.pos;){var p=Math.min(f.pos,u+5e4);i(p,c);u=p}}function gi(t,e,n,r){var i=[t.state.modeGen],o={};pi(t,e.text,t.doc.mode,n,function(t,e){i.push(t,e)},o,r);for(var a=0;a<t.state.overlays.length;++a){var s=t.state.overlays[a],l=1,u=0;pi(t,e.text,s.mode,!0,function(t,e){for(var n=l;t>u;){var r=i[l];r>t&&i.splice(l,1,t,i[l+1],r);l+=2;u=Math.min(t,r)}if(e)if(s.opaque){i.splice(n,l-n,t,"cm-overlay "+e);l=n+2}else for(;l>n;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"cm-overlay "+e}},o)}return{styles:i,classes:o.bgClass||o.textClass?o:null}}function mi(t,e,n){if(!e.styles||e.styles[0]!=t.state.modeGen){var r=gi(t,e,e.stateAfter=Te(t,Hi(e)));e.styles=r.styles;r.classes?e.styleClasses=r.classes:e.styleClasses&&(e.styleClasses=null);n===t.doc.frontier&&t.doc.frontier++}return e.styles}function vi(t,e,n,r){var i=t.doc.mode,o=new $a(e,t.options.tabSize);o.start=o.pos=r||0;""==e&&fi(i,n);for(;!o.eol()&&o.pos<=t.options.maxHighlightLength;){hi(i,o,n);o.start=o.pos}}function yi(t,e){if(!t||/^\s*$/.test(t))return null;var n=e.addModeClass?es:ts;return n[t]||(n[t]=t.replace(/\S+/g,"cm-$&"))}function bi(t,e){var n=So("span",null,null,ea?"padding-right: .1px":null),r={pre:So("pre",[n]),content:n,col:0,pos:0,cm:t};e.measure={};for(var i=0;i<=(e.rest?e.rest.length:0);i++){var o,a=i?e.rest[i-1]:e.line;r.pos=0;r.addToken=wi;(Qo||ea)&&t.getOption("lineWrapping")&&(r.addToken=Ci(r.addToken));Po(t.display.measure)&&(o=Ri(a))&&(r.addToken=Si(r.addToken,o));r.map=[];var s=e!=t.display.externalMeasured&&Hi(a);ki(a,r,mi(t,a,s));if(a.styleClasses){a.styleClasses.bgClass&&(r.bgClass=Lo(a.styleClasses.bgClass,r.bgClass||""));a.styleClasses.textClass&&(r.textClass=Lo(a.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Io(t.display.measure)));if(0==i){e.measure.map=r.map;e.measure.cache={}}else{(e.measure.maps||(e.measure.maps=[])).push(r.map);(e.measure.caches||(e.measure.caches=[])).push({})}}ea&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");fs(t,"renderLine",t,e.line,r.pre);r.pre.className&&(r.textClass=Lo(r.pre.className,r.textClass||""));return r}function xi(t){var e=So("span","•","cm-invalidchar");e.title="\\u"+t.charCodeAt(0).toString(16);return e}function wi(t,e,n,r,i,o){if(e){var a=t.cm.options.specialChars,s=!1;if(a.test(e))for(var l=document.createDocumentFragment(),u=0;;){a.lastIndex=u;var c=a.exec(e),f=c?c.index-u:e.length-u;if(f){var h=document.createTextNode(e.slice(u,u+f));l.appendChild(Qo&&9>ta?So("span",[h]):h);t.map.push(t.pos,t.pos+f,h);t.col+=f;t.pos+=f}if(!c)break;u+=f+1;if(" "==c[0]){var d=t.cm.options.tabSize,p=d-t.col%d,h=l.appendChild(So("span",ho(p),"cm-tab"));t.col+=p}else{var h=t.cm.options.specialCharPlaceholder(c[0]);l.appendChild(Qo&&9>ta?So("span",[h]):h);t.col+=1}t.map.push(t.pos,t.pos+1,h);t.pos++}else{t.col+=e.length;var l=document.createTextNode(e);t.map.push(t.pos,t.pos+e.length,l);Qo&&9>ta&&(s=!0);t.pos+=e.length}if(n||r||i||s){var g=n||"";r&&(g+=r);i&&(g+=i);var m=So("span",[l],g);o&&(m.title=o);return t.content.appendChild(m)}t.content.appendChild(l)}}function Ci(t){function e(t){for(var e=" ",n=0;n<t.length-2;++n)e+=n%2?" ":" ";e+=" ";return e}return function(n,r,i,o,a,s){t(n,r.replace(/ {3,}/g,e),i,o,a,s)}}function Si(t,e){return function(n,r,i,o,a,s){i=i?i+" cm-force-border":"cm-force-border";for(var l=n.pos,u=l+r.length;;){for(var c=0;c<e.length;c++){var f=e[c];if(f.to>l&&f.from<=l)break}if(f.to>=u)return t(n,r,i,o,a,s);t(n,r.slice(0,f.to-l),i,o,null,s);o=null;r=r.slice(f.to-l);l=f.to}}}function Ti(t,e,n,r){var i=!r&&n.widgetNode;if(i){t.map.push(t.pos,t.pos+e,i);t.content.appendChild(i)}t.pos+=e}function ki(t,e,n){var r=t.markedSpans,i=t.text,o=0;if(r)for(var a,s,l,u,c,f,h=i.length,d=0,p=1,g="",m=0;;){if(m==d){s=l=u=c="";f=null;m=1/0;for(var v=[],y=0;y<r.length;++y){var b=r[y],x=b.marker;if(b.from<=d&&(null==b.to||b.to>d)){if(null!=b.to&&m>b.to){m=b.to;l=""}x.className&&(s+=" "+x.className);x.startStyle&&b.from==d&&(u+=" "+x.startStyle);x.endStyle&&b.to==m&&(l+=" "+x.endStyle);x.title&&!c&&(c=x.title);x.collapsed&&(!f||$r(f.marker,x)<0)&&(f=b)}else b.from>d&&m>b.from&&(m=b.from);"bookmark"==x.type&&b.from==d&&x.widgetNode&&v.push(x)}if(f&&(f.from||0)==d){Ti(e,(null==f.to?h+1:f.to)-d,f.marker,null==f.from);if(null==f.to)return}if(!f&&v.length)for(var y=0;y<v.length;++y)Ti(e,0,v[y])}if(d>=h)break;for(var w=Math.min(h,m);;){if(g){var C=d+g.length;if(!f){var S=C>w?g.slice(0,w-d):g;e.addToken(e,S,a?a+s:s,u,d+S.length==m?l:"",c)}if(C>=w){g=g.slice(w-d);d=w;break}d=C;u=""}g=i.slice(o,o=n[p++]);a=yi(n[p++],e.cm.options)}}else for(var p=1;p<n.length;p+=2)e.addToken(e,i.slice(o,o=n[p]),yi(n[p+1],e.cm.options))}function _i(t,e){return 0==e.from.ch&&0==e.to.ch&&""==po(e.text)&&(!t.cm||t.cm.options.wholeLineUpdateBefore)}function Mi(t,e,n,r){function i(t){return n?n[t]:null}function o(t,n,i){li(t,n,i,r);io(t,"change",t,e)}var a=e.from,s=e.to,l=e.text,u=Ei(t,a.line),c=Ei(t,s.line),f=po(l),h=i(l.length-1),d=s.line-a.line;if(_i(t,e)){for(var p=0,g=[];p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));o(c,c.text,h);d&&t.remove(a.line,d);g.length&&t.insert(a.line,g)}else if(u==c)if(1==l.length)o(u,u.text.slice(0,a.ch)+f+u.text.slice(s.ch),h);else{for(var g=[],p=1;p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));g.push(new Qa(f+u.text.slice(s.ch),h,r));o(u,u.text.slice(0,a.ch)+l[0],i(0));t.insert(a.line+1,g)}else if(1==l.length){o(u,u.text.slice(0,a.ch)+l[0]+c.text.slice(s.ch),i(0));t.remove(a.line+1,d)}else{o(u,u.text.slice(0,a.ch)+l[0],i(0));o(c,f+c.text.slice(s.ch),h);for(var p=1,g=[];p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));d>1&&t.remove(a.line+1,d-1);t.insert(a.line+1,g)}io(t,"change",t,e)}function Di(t){this.lines=t;this.parent=null;for(var e=0,n=0;e<t.length;++e){t[e].parent=this;n+=t[e].height}this.height=n}function Li(t){this.children=t;for(var e=0,n=0,r=0;r<t.length;++r){var i=t[r];e+=i.chunkSize();n+=i.height;i.parent=this}this.size=e;this.height=n;this.parent=null}function Ai(t,e,n){function r(t,i,o){if(t.linked)for(var a=0;a<t.linked.length;++a){var s=t.linked[a];if(s.doc!=i){var l=o&&s.sharedHist;if(!n||l){e(s.doc,l);r(s.doc,t,l)}}}}r(t,null,!0)}function Ni(t,e){if(e.cm)throw new Error("This document is already in use.");t.doc=e;e.cm=t;a(t);n(t);t.options.lineWrapping||h(t);t.options.mode=e.modeOption;pn(t)}function Ei(t,e){e-=t.first;if(0>e||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var n=t;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(o>e){n=i;break}e-=o}return n.lines[e]}function ji(t,e,n){var r=[],i=e.line;t.iter(e.line,n.line+1,function(t){var o=t.text;i==n.line&&(o=o.slice(0,n.ch));i==e.line&&(o=o.slice(e.ch));r.push(o);++i});return r}function Ii(t,e,n){var r=[];t.iter(e,n,function(t){r.push(t.text)});return r}function Pi(t,e){var n=e-t.height;if(n)for(var r=t;r;r=r.parent)r.height+=n}function Hi(t){if(null==t.parent)return null;for(var e=t.parent,n=go(e.lines,t),r=e.parent;r;e=r,r=r.parent)for(var i=0;r.children[i]!=e;++i)n+=r.children[i].chunkSize();return n+e.first}function Oi(t,e){var n=t.first;t:do{for(var r=0;r<t.children.length;++r){var i=t.children[r],o=i.height;if(o>e){t=i;continue t}e-=o;n+=i.chunkSize()}return n}while(!t.lines);for(var r=0;r<t.lines.length;++r){var a=t.lines[r],s=a.height;if(s>e)break;e-=s}return n+r}function Fi(t){t=Qr(t);for(var e=0,n=t.parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==t)break;e+=i.height}for(var o=n.parent;o;n=o,o=n.parent)for(var r=0;r<o.children.length;++r){var a=o.children[r];if(a==n)break;e+=a.height}return e}function Ri(t){var e=t.order;null==e&&(e=t.order=Fs(t.text));return e}function Wi(t){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=t||1}function zi(t,e){var n={from:B(e.from),to:Ea(e),text:ji(t,e.from,e.to)};$i(t,n,e.from.line,e.to.line+1);Ai(t,function(t){$i(t,n,e.from.line,e.to.line+1)},!0);return n}function qi(t){for(;t.length;){var e=po(t);if(!e.ranges)break;t.pop()}}function Ui(t,e){if(e){qi(t.done);return po(t.done)}if(t.done.length&&!po(t.done).ranges)return po(t.done);if(t.done.length>1&&!t.done[t.done.length-2].ranges){t.done.pop();return po(t.done)}}function Bi(t,e,n,r){var i=t.history;i.undone.length=0;var o,a=+new Date;if((i.lastOp==r||i.lastOrigin==e.origin&&e.origin&&("+"==e.origin.charAt(0)&&t.cm&&i.lastModTime>a-t.cm.options.historyEventDelay||"*"==e.origin.charAt(0)))&&(o=Ui(i,i.lastOp==r))){var s=po(o.changes);0==ba(e.from,e.to)&&0==ba(e.from,s.to)?s.to=Ea(e):o.changes.push(zi(t,e))}else{var l=po(i.done);l&&l.ranges||Gi(t.sel,i.done);o={changes:[zi(t,e)],generation:i.generation};i.done.push(o);for(;i.done.length>i.undoDepth;){i.done.shift();i.done[0].ranges||i.done.shift()}}i.done.push(n);i.generation=++i.maxGeneration;i.lastModTime=i.lastSelTime=a;i.lastOp=i.lastSelOp=r;i.lastOrigin=i.lastSelOrigin=e.origin;s||fs(t,"historyAdded")}function Vi(t,e,n,r){var i=e.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}function Xi(t,e,n,r){var i=t.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||Vi(t,o,po(i.done),e))?i.done[i.done.length-1]=e:Gi(e,i.done);i.lastSelTime=+new Date;i.lastSelOrigin=o;i.lastSelOp=n;r&&r.clearRedo!==!1&&qi(i.undone)}function Gi(t,e){var n=po(e);n&&n.ranges&&n.equals(t)||e.push(t)}function $i(t,e,n,r){var i=e["spans_"+t.id],o=0;t.iter(Math.max(t.first,n),Math.min(t.first+t.size,r),function(n){n.markedSpans&&((i||(i=e["spans_"+t.id]={}))[o]=n.markedSpans);++o})}function Yi(t){if(!t)return null;for(var e,n=0;n<t.length;++n)t[n].marker.explicitlyCleared?e||(e=t.slice(0,n)):e&&e.push(t[n]);return e?e.length?e:null:t}function Ji(t,e){var n=e["spans_"+t.id];if(!n)return null;for(var r=0,i=[];r<e.text.length;++r)i.push(Yi(n[r]));return i}function Ki(t,e,n){for(var r=0,i=[];r<t.length;++r){var o=t[r];if(o.ranges)i.push(n?G.prototype.deepCopy.call(o):o);else{var a=o.changes,s=[];i.push({changes:s});for(var l=0;l<a.length;++l){var u,c=a[l];s.push({from:c.from,to:c.to,text:c.text});if(e)for(var f in c)if((u=f.match(/^spans_(\d+)$/))&&go(e,Number(u[1]))>-1){po(s)[f]=c[f];delete c[f]}}}}return i}function Zi(t,e,n,r){if(n<t.line)t.line+=r;else if(e<t.line){t.line=e;t.ch=0}}function Qi(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i],a=!0;if(o.ranges){if(!o.copied){o=t[i]=o.deepCopy();o.copied=!0}for(var s=0;s<o.ranges.length;s++){Zi(o.ranges[s].anchor,e,n,r);Zi(o.ranges[s].head,e,n,r)}}else{for(var s=0;s<o.changes.length;++s){var l=o.changes[s];if(n<l.from.line){l.from=ya(l.from.line+r,l.from.ch);l.to=ya(l.to.line+r,l.to.ch)}else if(e<=l.to.line){a=!1;break}}if(!a){t.splice(0,i+1);i=0}}}}function to(t,e){var n=e.from.line,r=e.to.line,i=e.text.length-(r-n)-1;Qi(t.done,n,r,i);Qi(t.undone,n,r,i)}function eo(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function no(t){return t.target||t.srcElement}function ro(t){var e=t.which;null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2));fa&&t.ctrlKey&&1==e&&(e=3);return e}function io(t,e){function n(t){return function(){t.apply(null,o)}}var r=t._handlers&&t._handlers[e];if(r){var i,o=Array.prototype.slice.call(arguments,2);if(Ta)i=Ta.delayedCallbacks;else if(hs)i=hs;else{i=hs=[];setTimeout(oo,0)}for(var a=0;a<r.length;++a)i.push(n(r[a]))}}function oo(){var t=hs;hs=null;for(var e=0;e<t.length;++e)t[e]()}function ao(t,e,n){"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}});fs(t,n||e.type,t,e);return eo(e)||e.codemirrorIgnore}function so(t){var e=t._handlers&&t._handlers.cursorActivity;if(e)for(var n=t.curOp.cursorActivityHandlers||(t.curOp.cursorActivityHandlers=[]),r=0;r<e.length;++r)-1==go(n,e[r])&&n.push(e[r])}function lo(t,e){var n=t._handlers&&t._handlers[e];return n&&n.length>0}function uo(t){t.prototype.on=function(t,e){us(this,t,e)};t.prototype.off=function(t,e){cs(this,t,e)}}function co(){this.id=null}function fo(t,e,n){for(var r=0,i=0;;){var o=t.indexOf(" ",r);-1==o&&(o=t.length);var a=o-r;if(o==t.length||i+a>=e)return r+Math.min(a,e-i);i+=o-r;i+=n-i%n;r=o+1;if(i>=e)return r}}function ho(t){for(;bs.length<=t;)bs.push(po(bs)+" ");return bs[t]}function po(t){return t[t.length-1]}function go(t,e){for(var n=0;n<t.length;++n)if(t[n]==e)return n;return-1}function mo(t,e){for(var n=[],r=0;r<t.length;r++)n[r]=e(t[r],r);return n}function vo(t,e){var n;if(Object.create)n=Object.create(t);else{var r=function(){};r.prototype=t;n=new r}e&&yo(e,n);return n}function yo(t,e,n){e||(e={});for(var r in t)!t.hasOwnProperty(r)||n===!1&&e.hasOwnProperty(r)||(e[r]=t[r]);return e}function bo(t){var e=Array.prototype.slice.call(arguments,1);return function(){return t.apply(null,e)}}function xo(t,e){return e?e.source.indexOf("\\w")>-1&&Ss(t)?!0:e.test(t):Ss(t)}function wo(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return!1;return!0}function Co(t){return t.charCodeAt(0)>=768&&Ts.test(t)}function So(t,e,n,r){var i=document.createElement(t);n&&(i.className=n);r&&(i.style.cssText=r);if("string"==typeof e)i.appendChild(document.createTextNode(e));else if(e)for(var o=0;o<e.length;++o)i.appendChild(e[o]);return i}function To(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function ko(t,e){return To(t).appendChild(e)}function _o(t,e){if(t.contains)return t.contains(e);for(;e=e.parentNode;)if(e==t)return!0}function Mo(){return document.activeElement}function Do(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}function Lo(t,e){for(var n=t.split(" "),r=0;r<n.length;r++)n[r]&&!Do(n[r]).test(e)&&(e+=" "+n[r]);return e}function Ao(t){if(document.body.getElementsByClassName)for(var e=document.body.getElementsByClassName("CodeMirror"),n=0;n<e.length;n++){var r=e[n].CodeMirror;r&&t(r)}}function No(){if(!As){Eo();As=!0}}function Eo(){var t;us(window,"resize",function(){null==t&&(t=setTimeout(function(){t=null;ks=null;Ao(Ln)},100))});us(window,"blur",function(){Ao(Qn)})}function jo(t){if(null!=ks)return ks;var e=So("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");ko(t,e);e.offsetWidth&&(ks=e.offsetHeight-e.clientHeight);return ks||0}function Io(t){if(null==_s){var e=So("span","​");ko(t,So("span",[e,document.createTextNode("x")]));0!=t.firstChild.offsetHeight&&(_s=e.offsetWidth<=1&&e.offsetHeight>2&&!(Qo&&8>ta))}return _s?So("span","​"):So("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Po(t){if(null!=Ms)return Ms;var e=ko(t,document.createTextNode("AخA")),n=ws(e,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=ws(e,1,2).getBoundingClientRect();return Ms=r.right-n.right<3}function Ho(t){if(null!=Ps)return Ps;var e=ko(t,So("span","x")),n=e.getBoundingClientRect(),r=ws(e,0,1).getBoundingClientRect();return Ps=Math.abs(n.left-r.left)>1}function Oo(t,e,n,r){if(!t)return r(e,n,"ltr");for(var i=!1,o=0;o<t.length;++o){var a=t[o];if(a.from<n&&a.to>e||e==n&&a.to==e){r(Math.max(a.from,e),Math.min(a.to,n),1==a.level?"rtl":"ltr");i=!0}}i||r(e,n,"ltr")}function Fo(t){return t.level%2?t.to:t.from}function Ro(t){return t.level%2?t.from:t.to}function Wo(t){var e=Ri(t);return e?Fo(e[0]):0}function zo(t){var e=Ri(t);return e?Ro(po(e)):t.text.length}function qo(t,e){var n=Ei(t.doc,e),r=Qr(n);r!=n&&(e=Hi(r));var i=Ri(r),o=i?i[0].level%2?zo(r):Wo(r):0;return ya(e,o)}function Uo(t,e){for(var n,r=Ei(t.doc,e);n=Kr(r);){r=n.find(1,!0).line;e=null}var i=Ri(r),o=i?i[0].level%2?Wo(r):zo(r):r.text.length;return ya(null==e?Hi(r):e,o)}function Bo(t,e){var n=qo(t,e.line),r=Ei(t.doc,n.line),i=Ri(r);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),a=e.line==n.line&&e.ch<=o&&e.ch;return ya(n.line,a?0:o)}return n}function Vo(t,e,n){var r=t[0].level;return e==r?!0:n==r?!1:n>e}function Xo(t,e){Os=null;for(var n,r=0;r<t.length;++r){var i=t[r];if(i.from<e&&i.to>e)return r;if(i.from==e||i.to==e){if(null!=n){if(Vo(t,i.level,t[n].level)){i.from!=i.to&&(Os=n);return r}i.from!=i.to&&(Os=r);return n}n=r}}return n}function Go(t,e,n,r){if(!r)return e+n;do e+=n;while(e>0&&Co(t.text.charAt(e)));return e}function $o(t,e,n,r){var i=Ri(t);if(!i)return Yo(t,e,n,r);for(var o=Xo(i,e),a=i[o],s=Go(t,e,a.level%2?-n:n,r);;){if(s>a.from&&s<a.to)return s;if(s==a.from||s==a.to){if(Xo(i,s)==o)return s;a=i[o+=n];return n>0==a.level%2?a.to:a.from}a=i[o+=n];if(!a)return null;s=n>0==a.level%2?Go(t,a.to,-1,r):Go(t,a.from,1,r)}}function Yo(t,e,n,r){var i=e+n;if(r)for(;i>0&&Co(t.text.charAt(i));)i+=n; return 0>i||i>t.text.length?null:i}var Jo=/gecko\/\d/i.test(navigator.userAgent),Ko=/MSIE \d/.test(navigator.userAgent),Zo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Qo=Ko||Zo,ta=Qo&&(Ko?document.documentMode||6:Zo[1]),ea=/WebKit\//.test(navigator.userAgent),na=ea&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ra=/Chrome\//.test(navigator.userAgent),ia=/Opera\//.test(navigator.userAgent),oa=/Apple Computer/.test(navigator.vendor),aa=/KHTML\//.test(navigator.userAgent),sa=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),la=/PhantomJS/.test(navigator.userAgent),ua=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),ca=ua||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),fa=ua||/Mac/.test(navigator.platform),ha=/win/i.test(navigator.platform),da=ia&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);da&&(da=Number(da[1]));if(da&&da>=15){ia=!1;ea=!0}var pa=fa&&(na||ia&&(null==da||12.11>da)),ga=Jo||Qo&&ta>=9,ma=!1,va=!1,ya=t.Pos=function(t,e){if(!(this instanceof ya))return new ya(t,e);this.line=t;this.ch=e},ba=t.cmpPos=function(t,e){return t.line-e.line||t.ch-e.ch};G.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(t){if(t==this)return!0;if(t.primIndex!=this.primIndex||t.ranges.length!=this.ranges.length)return!1;for(var e=0;e<this.ranges.length;e++){var n=this.ranges[e],r=t.ranges[e];if(0!=ba(n.anchor,r.anchor)||0!=ba(n.head,r.head))return!1}return!0},deepCopy:function(){for(var t=[],e=0;e<this.ranges.length;e++)t[e]=new $(B(this.ranges[e].anchor),B(this.ranges[e].head));return new G(t,this.primIndex)},somethingSelected:function(){for(var t=0;t<this.ranges.length;t++)if(!this.ranges[t].empty())return!0;return!1},contains:function(t,e){e||(e=t);for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(ba(e,r.from())>=0&&ba(t,r.to())<=0)return n}return-1}};$.prototype={from:function(){return X(this.anchor,this.head)},to:function(){return V(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var xa,wa,Ca,Sa={left:0,right:0,top:0,bottom:0},Ta=null,ka=0,_a=null,Ma=0,Da=0,La=null;Qo?La=-.53:Jo?La=15:ra?La=-.7:oa&&(La=-1/3);var Aa=new co,Na=null,Ea=t.changeEnd=function(t){return t.text?ya(t.from.line+t.text.length-1,po(t.text).length+(1==t.text.length?t.from.ch:0)):t.to};t.prototype={constructor:t,focus:function(){window.focus();kn(this);Cn(this)},setOption:function(t,e){var n=this.options,r=n[t];if(n[t]!=e||"mode"==t){n[t]=e;Ia.hasOwnProperty(t)&&un(this,Ia[t])(this,e,r)}},getOption:function(t){return this.options[t]},getDoc:function(){return this.doc},addKeyMap:function(t,e){this.state.keyMaps[e?"push":"unshift"](Dr(t))},removeKeyMap:function(t){for(var e=this.state.keyMaps,n=0;n<e.length;++n)if(e[n]==t||e[n].name==t){e.splice(n,1);return!0}},addOverlay:cn(function(e,n){var r=e.token?e:t.getMode(this.options,e);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:e,opaque:n&&n.opaque});this.state.modeGen++;pn(this)}),removeOverlay:cn(function(t){for(var e=this.state.overlays,n=0;n<e.length;++n){var r=e[n].modeSpec;if(r==t||"string"==typeof t&&r.name==t){e.splice(n,1);this.state.modeGen++;pn(this);return}}}),indentLine:cn(function(t,e,n){"string"!=typeof e&&"number"!=typeof e&&(e=null==e?this.options.smartIndent?"smart":"prev":e?"add":"subtract");te(this.doc,t)&&wr(this,t,e,n)}),indentSelection:cn(function(t){for(var e=this.doc.sel.ranges,n=-1,r=0;r<e.length;r++){var i=e[r];if(i.empty()){if(i.head.line>n){wr(this,i.head.line,t,!0);n=i.head.line;r==this.doc.sel.primIndex&&br(this)}}else{var o=i.from(),a=i.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;n>l;++l)wr(this,l,t);var u=this.doc.sel.ranges;0==o.ch&&e.length==u.length&&u[r].from().ch>0&&oe(this.doc,r,new $(o,u[r].to()),gs)}}}),getTokenAt:function(t,e){return di(this,t,e)},getLineTokens:function(t,e){return di(this,ya(t),e,!0)},getTokenTypeAt:function(t){t=Z(this.doc,t);var e,n=mi(this,Ei(this.doc,t.line)),r=0,i=(n.length-1)/2,o=t.ch;if(0==o)e=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]<o)){e=n[2*a+2];break}r=a+1}}var s=e?e.indexOf("cm-overlay "):-1;return 0>s?e:0==s?null:e.slice(0,s-1)},getModeAt:function(e){var n=this.doc.mode;return n.innerMode?t.innerMode(n,this.getTokenAt(e).state).mode:n},getHelper:function(t,e){return this.getHelpers(t,e)[0]},getHelpers:function(t,e){var n=[];if(!Wa.hasOwnProperty(e))return Wa;var r=Wa[e],i=this.getModeAt(t);if("string"==typeof i[e])r[i[e]]&&n.push(r[i[e]]);else if(i[e])for(var o=0;o<i[e].length;o++){var a=r[i[e][o]];a&&n.push(a)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var o=0;o<r._global.length;o++){var s=r._global[o];s.pred(i,this)&&-1==go(n,s.val)&&n.push(s.val)}return n},getStateAfter:function(t,e){var n=this.doc;t=K(n,null==t?n.first+n.size-1:t);return Te(this,t+1,e)},cursorCoords:function(t,e){var n,r=this.doc.sel.primary();n=null==t?r.head:"object"==typeof t?Z(this.doc,t):t?r.from():r.to();return Ve(this,n,e||"page")},charCoords:function(t,e){return Be(this,Z(this.doc,t),e||"page")},coordsChar:function(t,e){t=Ue(this,t,e||"page");return $e(this,t.left,t.top)},lineAtHeight:function(t,e){t=Ue(this,{top:t,left:0},e||"page").top;return Oi(this.doc,t+this.display.viewOffset)},heightAtLine:function(t,e){var n=!1,r=this.doc.first+this.doc.size-1;if(t<this.doc.first)t=this.doc.first;else if(t>r){t=r;n=!0}var i=Ei(this.doc,t);return qe(this,i,{top:0,left:0},e||"page").top+(n?this.doc.height-Fi(i):0)},defaultTextHeight:function(){return Je(this.display)},defaultCharWidth:function(){return Ke(this.display)},setGutterMarker:cn(function(t,e,n){return Cr(this.doc,t,"gutter",function(t){var r=t.gutterMarkers||(t.gutterMarkers={});r[e]=n;!n&&wo(r)&&(t.gutterMarkers=null);return!0})}),clearGutter:cn(function(t){var e=this,n=e.doc,r=n.first;n.iter(function(n){if(n.gutterMarkers&&n.gutterMarkers[t]){n.gutterMarkers[t]=null;gn(e,r,"gutter");wo(n.gutterMarkers)&&(n.gutterMarkers=null)}++r})}),addLineWidget:cn(function(t,e,n){return si(this,t,e,n)}),removeLineWidget:function(t){t.clear()},lineInfo:function(t){if("number"==typeof t){if(!te(this.doc,t))return null;var e=t;t=Ei(this.doc,t);if(!t)return null}else{var e=Hi(t);if(null==e)return null}return{line:e,handle:t,text:t.text,gutterMarkers:t.gutterMarkers,textClass:t.textClass,bgClass:t.bgClass,wrapClass:t.wrapClass,widgets:t.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,n,r,i){var o=this.display;t=Ve(this,Z(this.doc,t));var a=t.bottom,s=t.left;e.style.position="absolute";o.sizer.appendChild(e);if("over"==r)a=t.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||t.bottom+e.offsetHeight>l)&&t.top>e.offsetHeight?a=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=l&&(a=t.bottom);s+e.offsetWidth>u&&(s=u-e.offsetWidth)}e.style.top=a+"px";e.style.left=e.style.right="";if("right"==i){s=o.sizer.clientWidth-e.offsetWidth;e.style.right="0px"}else{"left"==i?s=0:"middle"==i&&(s=(o.sizer.clientWidth-e.offsetWidth)/2);e.style.left=s+"px"}n&&mr(this,s,a,s+e.offsetWidth,a+e.offsetHeight)},triggerOnKeyDown:cn($n),triggerOnKeyPress:cn(Kn),triggerOnKeyUp:Jn,execCommand:function(t){return Ua.hasOwnProperty(t)?Ua[t](this):void 0},findPosH:function(t,e,n,r){var i=1;if(0>e){i=-1;e=-e}for(var o=0,a=Z(this.doc,t);e>o;++o){a=Tr(this.doc,a,i,n,r);if(a.hitSide)break}return a},moveH:cn(function(t,e){var n=this;n.extendSelectionsBy(function(r){return n.display.shift||n.doc.extend||r.empty()?Tr(n.doc,r.head,t,e,n.options.rtlMoveVisually):0>t?r.from():r.to()},vs)}),deleteH:cn(function(t,e){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):Sr(this,function(n){var i=Tr(r,n.head,t,e,!1);return 0>t?{from:i,to:n.head}:{from:n.head,to:i}})}),findPosV:function(t,e,n,r){var i=1,o=r;if(0>e){i=-1;e=-e}for(var a=0,s=Z(this.doc,t);e>a;++a){var l=Ve(this,s,"div");null==o?o=l.left:l.left=o;s=kr(this,l,i,n);if(s.hitSide)break}return s},moveV:cn(function(t,e){var n=this,r=this.doc,i=[],o=!n.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(a){if(o)return 0>t?a.from():a.to();var s=Ve(n,a.head,"div");null!=a.goalColumn&&(s.left=a.goalColumn);i.push(s.left);var l=kr(n,s,t,e);"page"==e&&a==r.sel.primary()&&yr(n,null,Be(n,l,"div").top-s.top);return l},vs);if(i.length)for(var a=0;a<r.sel.ranges.length;a++)r.sel.ranges[a].goalColumn=i[a]}),findWordAt:function(t){var e=this.doc,n=Ei(e,t.line).text,r=t.ch,i=t.ch;if(n){var o=this.getHelper(t,"wordChars");(t.xRel<0||i==n.length)&&r?--r:++i;for(var a=n.charAt(r),s=xo(a,o)?function(t){return xo(t,o)}:/\s/.test(a)?function(t){return/\s/.test(t)}:function(t){return!/\s/.test(t)&&!xo(t)};r>0&&s(n.charAt(r-1));)--r;for(;i<n.length&&s(n.charAt(i));)++i}return new $(ya(t.line,r),ya(t.line,i))},toggleOverwrite:function(t){if(null==t||t!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?Ls(this.display.cursorDiv,"CodeMirror-overwrite"):Ds(this.display.cursorDiv,"CodeMirror-overwrite");fs(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return Mo()==this.display.input},scrollTo:cn(function(t,e){(null!=t||null!=e)&&xr(this);null!=t&&(this.curOp.scrollLeft=t);null!=e&&(this.curOp.scrollTop=e)}),getScrollInfo:function(){var t=this.display.scroller,e=ds;return{left:t.scrollLeft,top:t.scrollTop,height:t.scrollHeight-e,width:t.scrollWidth-e,clientHeight:t.clientHeight-e,clientWidth:t.clientWidth-e}},scrollIntoView:cn(function(t,e){if(null==t){t={from:this.doc.sel.primary().head,to:null};null==e&&(e=this.options.cursorScrollMargin)}else"number"==typeof t?t={from:ya(t,0),to:null}:null==t.from&&(t={from:t,to:null});t.to||(t.to=t.from);t.margin=e||0;if(null!=t.from.line){xr(this);this.curOp.scrollToPos=t}else{var n=vr(this,Math.min(t.from.left,t.to.left),Math.min(t.from.top,t.to.top)-t.margin,Math.max(t.from.right,t.to.right),Math.max(t.from.bottom,t.to.bottom)+t.margin);this.scrollTo(n.scrollLeft,n.scrollTop)}}),setSize:cn(function(t,e){function n(t){return"number"==typeof t||/^\d+$/.test(String(t))?t+"px":t}var r=this;null!=t&&(r.display.wrapper.style.width=n(t));null!=e&&(r.display.wrapper.style.height=n(e));r.options.lineWrapping&&Fe(this);var i=r.display.viewFrom;r.doc.iter(i,r.display.viewTo,function(t){if(t.widgets)for(var e=0;e<t.widgets.length;e++)if(t.widgets[e].noHScroll){gn(r,i,"widget");break}++i});r.curOp.forceUpdate=!0;fs(r,"refresh",this)}),operation:function(t){return ln(this,t)},refresh:cn(function(){var t=this.display.cachedTextHeight;pn(this);this.curOp.forceUpdate=!0;Re(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);c(this);(null==t||Math.abs(t-Je(this.display))>.5)&&a(this);fs(this,"refresh",this)}),swapDoc:cn(function(t){var e=this.doc;e.cm=null;Ni(this,t);Re(this);Tn(this);this.scrollTo(t.scrollLeft,t.scrollTop);this.curOp.forceScroll=!0;io(this,"swapDoc",this,e);return e}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};uo(t);var ja=t.defaults={},Ia=t.optionHandlers={},Pa=t.Init={toString:function(){return"CodeMirror.Init"}};_r("value","",function(t,e){t.setValue(e)},!0);_r("mode",null,function(t,e){t.doc.modeOption=e;n(t)},!0);_r("indentUnit",2,n,!0);_r("indentWithTabs",!1);_r("smartIndent",!0);_r("tabSize",4,function(t){r(t);Re(t);pn(t)},!0);_r("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(t,e){t.options.specialChars=new RegExp(e.source+(e.test(" ")?"":"| "),"g");t.refresh()},!0);_r("specialCharPlaceholder",xi,function(t){t.refresh()},!0);_r("electricChars",!0);_r("rtlMoveVisually",!ha);_r("wholeLineUpdateBefore",!0);_r("theme","default",function(t){s(t);l(t)},!0);_r("keyMap","default",function(e,n,r){var i=Dr(n),o=r!=t.Init&&Dr(r);o&&o.detach&&o.detach(e,i);i.attach&&i.attach(e,o||null)});_r("extraKeys",null);_r("lineWrapping",!1,i,!0);_r("gutters",[],function(t){d(t.options);l(t)},!0);_r("fixedGutter",!0,function(t,e){t.display.gutters.style.left=e?w(t.display)+"px":"0";t.refresh()},!0);_r("coverGutterNextToScrollbar",!1,m,!0);_r("lineNumbers",!1,function(t){d(t.options);l(t)},!0);_r("firstLineNumber",1,l,!0);_r("lineNumberFormatter",function(t){return t},l,!0);_r("showCursorWhenSelecting",!1,ve,!0);_r("resetSelectionOnContextMenu",!0);_r("readOnly",!1,function(t,e){if("nocursor"==e){Qn(t);t.display.input.blur();t.display.disabled=!0}else{t.display.disabled=!1;e||Tn(t)}});_r("disableInput",!1,function(t,e){e||Tn(t)},!0);_r("dragDrop",!0);_r("cursorBlinkRate",530);_r("cursorScrollMargin",0);_r("cursorHeight",1,ve,!0);_r("singleCursorHeightPerLine",!0,ve,!0);_r("workTime",100);_r("workDelay",100);_r("flattenSpans",!0,r,!0);_r("addModeClass",!1,r,!0);_r("pollInterval",100);_r("undoDepth",200,function(t,e){t.doc.history.undoDepth=e});_r("historyEventDelay",1250);_r("viewportMargin",10,function(t){t.refresh()},!0);_r("maxHighlightLength",1e4,r,!0);_r("moveInputWithCursor",!0,function(t,e){e||(t.display.inputDiv.style.top=t.display.inputDiv.style.left=0)});_r("tabindex",null,function(t,e){t.display.input.tabIndex=e||""});_r("autofocus",null);var Ha=t.modes={},Oa=t.mimeModes={};t.defineMode=function(e,n){t.defaults.mode||"null"==e||(t.defaults.mode=e);arguments.length>2&&(n.dependencies=Array.prototype.slice.call(arguments,2));Ha[e]=n};t.defineMIME=function(t,e){Oa[t]=e};t.resolveMode=function(e){if("string"==typeof e&&Oa.hasOwnProperty(e))e=Oa[e];else if(e&&"string"==typeof e.name&&Oa.hasOwnProperty(e.name)){var n=Oa[e.name];"string"==typeof n&&(n={name:n});e=vo(n,e);e.name=n.name}else if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return t.resolveMode("application/xml");return"string"==typeof e?{name:e}:e||{name:"null"}};t.getMode=function(e,n){var n=t.resolveMode(n),r=Ha[n.name];if(!r)return t.getMode(e,"text/plain");var i=r(e,n);if(Fa.hasOwnProperty(n.name)){var o=Fa[n.name];for(var a in o)if(o.hasOwnProperty(a)){i.hasOwnProperty(a)&&(i["_"+a]=i[a]);i[a]=o[a]}}i.name=n.name;n.helperType&&(i.helperType=n.helperType);if(n.modeProps)for(var a in n.modeProps)i[a]=n.modeProps[a];return i};t.defineMode("null",function(){return{token:function(t){t.skipToEnd()}}});t.defineMIME("text/plain","null");var Fa=t.modeExtensions={};t.extendMode=function(t,e){var n=Fa.hasOwnProperty(t)?Fa[t]:Fa[t]={};yo(e,n)};t.defineExtension=function(e,n){t.prototype[e]=n};t.defineDocExtension=function(t,e){rs.prototype[t]=e};t.defineOption=_r;var Ra=[];t.defineInitHook=function(t){Ra.push(t)};var Wa=t.helpers={};t.registerHelper=function(e,n,r){Wa.hasOwnProperty(e)||(Wa[e]=t[e]={_global:[]});Wa[e][n]=r};t.registerGlobalHelper=function(e,n,r,i){t.registerHelper(e,n,i);Wa[e]._global.push({pred:r,val:i})};var za=t.copyState=function(t,e){if(e===!0)return e;if(t.copyState)return t.copyState(e);var n={};for(var r in e){var i=e[r];i instanceof Array&&(i=i.concat([]));n[r]=i}return n},qa=t.startState=function(t,e,n){return t.startState?t.startState(e,n):!0};t.innerMode=function(t,e){for(;t.innerMode;){var n=t.innerMode(e);if(!n||n.mode==t)break;e=n.state;t=n.mode}return n||{mode:t,state:e}};var Ua=t.commands={selectAll:function(t){t.setSelection(ya(t.firstLine(),0),ya(t.lastLine()),gs)},singleSelection:function(t){t.setSelection(t.getCursor("anchor"),t.getCursor("head"),gs)},killLine:function(t){Sr(t,function(e){if(e.empty()){var n=Ei(t.doc,e.head.line).text.length;return e.head.ch==n&&e.head.line<t.lastLine()?{from:e.head,to:ya(e.head.line+1,0)}:{from:e.head,to:ya(e.head.line,n)}}return{from:e.from(),to:e.to()}})},deleteLine:function(t){Sr(t,function(e){return{from:ya(e.from().line,0),to:Z(t.doc,ya(e.to().line+1,0))}})},delLineLeft:function(t){Sr(t,function(t){return{from:ya(t.from().line,0),to:t.from()}})},delWrappedLineLeft:function(t){Sr(t,function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:0,top:n},"div");return{from:r,to:e.from()}})},delWrappedLineRight:function(t){Sr(t,function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:t.display.lineDiv.offsetWidth+100,top:n},"div");return{from:e.from(),to:r}})},undo:function(t){t.undo()},redo:function(t){t.redo()},undoSelection:function(t){t.undoSelection()},redoSelection:function(t){t.redoSelection()},goDocStart:function(t){t.extendSelection(ya(t.firstLine(),0))},goDocEnd:function(t){t.extendSelection(ya(t.lastLine()))},goLineStart:function(t){t.extendSelectionsBy(function(e){return qo(t,e.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(t){t.extendSelectionsBy(function(e){return Bo(t,e.head)},{origin:"+move",bias:1})},goLineEnd:function(t){t.extendSelectionsBy(function(e){return Uo(t,e.head.line)},{origin:"+move",bias:-1})},goLineRight:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5;return t.coordsChar({left:t.display.lineDiv.offsetWidth+100,top:n},"div")},vs)},goLineLeft:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5;return t.coordsChar({left:0,top:n},"div")},vs)},goLineLeftSmart:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:0,top:n},"div");return r.ch<t.getLine(r.line).search(/\S/)?Bo(t,e.head):r},vs)},goLineUp:function(t){t.moveV(-1,"line")},goLineDown:function(t){t.moveV(1,"line")},goPageUp:function(t){t.moveV(-1,"page")},goPageDown:function(t){t.moveV(1,"page")},goCharLeft:function(t){t.moveH(-1,"char")},goCharRight:function(t){t.moveH(1,"char")},goColumnLeft:function(t){t.moveH(-1,"column")},goColumnRight:function(t){t.moveH(1,"column")},goWordLeft:function(t){t.moveH(-1,"word")},goGroupRight:function(t){t.moveH(1,"group")},goGroupLeft:function(t){t.moveH(-1,"group")},goWordRight:function(t){t.moveH(1,"word")},delCharBefore:function(t){t.deleteH(-1,"char")},delCharAfter:function(t){t.deleteH(1,"char")},delWordBefore:function(t){t.deleteH(-1,"word")},delWordAfter:function(t){t.deleteH(1,"word")},delGroupBefore:function(t){t.deleteH(-1,"group")},delGroupAfter:function(t){t.deleteH(1,"group")},indentAuto:function(t){t.indentSelection("smart")},indentMore:function(t){t.indentSelection("add")},indentLess:function(t){t.indentSelection("subtract")},insertTab:function(t){t.replaceSelection(" ")},insertSoftTab:function(t){for(var e=[],n=t.listSelections(),r=t.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),a=ys(t.getLine(o.line),o.ch,r);e.push(new Array(r-a%r+1).join(" "))}t.replaceSelections(e)},defaultTab:function(t){t.somethingSelected()?t.indentSelection("add"):t.execCommand("insertTab")},transposeChars:function(t){ln(t,function(){for(var e=t.listSelections(),n=[],r=0;r<e.length;r++){var i=e[r].head,o=Ei(t.doc,i.line).text;if(o){i.ch==o.length&&(i=new ya(i.line,i.ch-1));if(i.ch>0){i=new ya(i.line,i.ch+1);t.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),ya(i.line,i.ch-2),i,"+transpose")}else if(i.line>t.doc.first){var a=Ei(t.doc,i.line-1).text;a&&t.replaceRange(o.charAt(0)+"\n"+a.charAt(a.length-1),ya(i.line-1,a.length-1),ya(i.line,1),"+transpose")}}n.push(new $(i,i))}t.setSelections(n)})},newlineAndIndent:function(t){ln(t,function(){for(var e=t.listSelections().length,n=0;e>n;n++){var r=t.listSelections()[n];t.replaceRange("\n",r.anchor,r.head,"+input");t.indentLine(r.from().line+1,null,!0);br(t)}})},toggleOverwrite:function(t){t.toggleOverwrite()}},Ba=t.keyMap={};Ba.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};Ba.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};Ba.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};Ba.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};Ba["default"]=fa?Ba.macDefault:Ba.pcDefault;t.normalizeKeyMap=function(t){var e={};for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];if(/^(name|fallthrough|(de|at)tach)$/.test(n))continue;if("..."==r){delete t[n];continue}for(var i=mo(n.split(" "),Mr),o=0;o<i.length;o++){var a,s;if(o==i.length-1){s=n;a=r}else{s=i.slice(0,o+1).join(" ");a="..."}var l=e[s];if(l){if(l!=a)throw new Error("Inconsistent bindings for "+s)}else e[s]=a}delete t[n]}for(var u in e)t[u]=e[u];return t};var Va=t.lookupKey=function(t,e,n){e=Dr(e);var r=e.call?e.call(t):e[t];if(r===!1)return"nothing";if("..."===r)return"multi";if(null!=r&&n(r))return"handled";if(e.fallthrough){if("[object Array]"!=Object.prototype.toString.call(e.fallthrough))return Va(t,e.fallthrough,n);for(var i=0;i<e.fallthrough.length;i++){var o=Va(t,e.fallthrough[i],n);if(o)return o}}},Xa=t.isModifierKey=function(t){var e="string"==typeof t?t:Hs[t.keyCode];return"Ctrl"==e||"Alt"==e||"Shift"==e||"Mod"==e},Ga=t.keyName=function(t,e){if(ia&&34==t.keyCode&&t["char"])return!1;var n=Hs[t.keyCode],r=n;if(null==r||t.altGraphKey)return!1;t.altKey&&"Alt"!=n&&(r="Alt-"+r);(pa?t.metaKey:t.ctrlKey)&&"Ctrl"!=n&&(r="Ctrl-"+r);(pa?t.ctrlKey:t.metaKey)&&"Cmd"!=n&&(r="Cmd-"+r);!e&&t.shiftKey&&"Shift"!=n&&(r="Shift-"+r);return r};t.fromTextArea=function(e,n){function r(){e.value=u.getValue()}n||(n={});n.value=e.value;!n.tabindex&&e.tabindex&&(n.tabindex=e.tabindex);!n.placeholder&&e.placeholder&&(n.placeholder=e.placeholder);if(null==n.autofocus){var i=Mo();n.autofocus=i==e||null!=e.getAttribute("autofocus")&&i==document.body}if(e.form){us(e.form,"submit",r);if(!n.leaveSubmitMethodAlone){var o=e.form,a=o.submit;try{var s=o.submit=function(){r();o.submit=a;o.submit();o.submit=s}}catch(l){}}}e.style.display="none";var u=t(function(t){e.parentNode.insertBefore(t,e.nextSibling)},n);u.save=r;u.getTextArea=function(){return e};u.toTextArea=function(){u.toTextArea=isNaN;r();e.parentNode.removeChild(u.getWrapperElement());e.style.display="";if(e.form){cs(e.form,"submit",r);"function"==typeof e.form.submit&&(e.form.submit=a)}};return u};var $a=t.StringStream=function(t,e){this.pos=this.start=0;this.string=t;this.tabSize=e||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};$a.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(t){var e=this.string.charAt(this.pos);if("string"==typeof t)var n=e==t;else var n=e&&(t.test?t.test(e):t(e));if(n){++this.pos;return e}},eatWhile:function(t){for(var e=this.pos;this.eat(t););return this.pos>e},eatSpace:function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},skipToEnd:function(){this.pos=this.string.length},skipTo:function(t){var e=this.string.indexOf(t,this.pos);if(e>-1){this.pos=e;return!0}},backUp:function(t){this.pos-=t},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ys(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ys(this.string,null,this.tabSize)-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},match:function(t,e,n){if("string"!=typeof t){var r=this.string.slice(this.pos).match(t);if(r&&r.index>0)return null;r&&e!==!1&&(this.pos+=r[0].length);return r}var i=function(t){return n?t.toLowerCase():t},o=this.string.substr(this.pos,t.length);if(i(o)==i(t)){e!==!1&&(this.pos+=t.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t}}};var Ya=t.TextMarker=function(t,e){this.lines=[];this.type=e;this.doc=t};uo(Ya);Ya.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;e&&Ze(t);if(lo(this,"clear")){var n=this.find();n&&io(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var a=this.lines[o],s=Pr(a.markedSpans,this);if(t&&!this.collapsed)gn(t,Hi(a),"text");else if(t){null!=s.to&&(i=Hi(a));null!=s.from&&(r=Hi(a))}a.markedSpans=Hr(a.markedSpans,s);null==s.from&&this.collapsed&&!ri(this.doc,a)&&t&&Pi(a,Je(t.display))}if(t&&this.collapsed&&!t.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Qr(this.lines[o]),u=f(l);if(u>t.display.maxLineLength){t.display.maxLine=l;t.display.maxLineLength=u;t.display.maxLineChanged=!0}}null!=r&&t&&this.collapsed&&pn(t,r,i+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;t&&he(t.doc)}t&&io(t,"markerCleared",t,this);e&&tn(t);this.parent&&this.parent.clear()}};Ya.prototype.find=function(t,e){null==t&&"bookmark"==this.type&&(t=1);for(var n,r,i=0;i<this.lines.length;++i){var o=this.lines[i],a=Pr(o.markedSpans,this);if(null!=a.from){n=ya(e?o:Hi(o),a.from);if(-1==t)return n}if(null!=a.to){r=ya(e?o:Hi(o),a.to);if(1==t)return r}}return n&&{from:n,to:r}};Ya.prototype.changed=function(){var t=this.find(-1,!0),e=this,n=this.doc.cm;t&&n&&ln(n,function(){var r=t.line,i=Hi(t.line),o=Ee(n,i);if(o){Oe(o);n.curOp.selectionChanged=n.curOp.forceUpdate=!0}n.curOp.updateMaxLine=!0;if(!ri(e.doc,r)&&null!=e.height){var a=e.height;e.height=null;var s=ai(e)-a;s&&Pi(r,r.height+s)}})};Ya.prototype.attachLine=function(t){if(!this.lines.length&&this.doc.cm){var e=this.doc.cm.curOp;e.maybeHiddenMarkers&&-1!=go(e.maybeHiddenMarkers,this)||(e.maybeUnhiddenMarkers||(e.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(t)};Ya.prototype.detachLine=function(t){this.lines.splice(go(this.lines,t),1);if(!this.lines.length&&this.doc.cm){var e=this.doc.cm.curOp;(e.maybeHiddenMarkers||(e.maybeHiddenMarkers=[])).push(this)}};var Ja=0,Ka=t.SharedTextMarker=function(t,e){this.markers=t;this.primary=e;for(var n=0;n<t.length;++n)t[n].parent=this};uo(Ka);Ka.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var t=0;t<this.markers.length;++t)this.markers[t].clear();io(this,"clear")}};Ka.prototype.find=function(t,e){return this.primary.find(t,e)};var Za=t.LineWidget=function(t,e,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.cm=t;this.node=e};uo(Za);Za.prototype.clear=function(){var t=this.cm,e=this.line.widgets,n=this.line,r=Hi(n);if(null!=r&&e){for(var i=0;i<e.length;++i)e[i]==this&&e.splice(i--,1);e.length||(n.widgets=null);var o=ai(this);ln(t,function(){oi(t,n,-o);gn(t,r,"widget");Pi(n,Math.max(0,n.height-o))})}};Za.prototype.changed=function(){var t=this.height,e=this.cm,n=this.line;this.height=null;var r=ai(this)-t;r&&ln(e,function(){e.curOp.forceUpdate=!0;oi(e,n,r);Pi(n,n.height+r)})};var Qa=t.Line=function(t,e,n){this.text=t;Vr(this,e);this.height=n?n(this):1};uo(Qa);Qa.prototype.lineNo=function(){return Hi(this)};var ts={},es={};Di.prototype={chunkSize:function(){return this.lines.length},removeInner:function(t,e){for(var n=t,r=t+e;r>n;++n){var i=this.lines[n];this.height-=i.height;ui(i);io(i,"delete")}this.lines.splice(t,e)},collapse:function(t){t.push.apply(t,this.lines)},insertInner:function(t,e,n){this.height+=n;this.lines=this.lines.slice(0,t).concat(e).concat(this.lines.slice(t));for(var r=0;r<e.length;++r)e[r].parent=this},iterN:function(t,e,n){for(var r=t+e;r>t;++t)if(n(this.lines[t]))return!0}};Li.prototype={chunkSize:function(){return this.size},removeInner:function(t,e){this.size-=e;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(i>t){var o=Math.min(e,i-t),a=r.height;r.removeInner(t,o);this.height-=a-r.height;if(i==o){this.children.splice(n--,1);r.parent=null}if(0==(e-=o))break;t=0}else t-=i}if(this.size-e<25&&(this.children.length>1||!(this.children[0]instanceof Di))){var s=[];this.collapse(s);this.children=[new Di(s)];this.children[0].parent=this}},collapse:function(t){for(var e=0;e<this.children.length;++e)this.children[e].collapse(t)},insertInner:function(t,e,n){this.size+=e.length;this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>=t){i.insertInner(t,e,n);if(i.lines&&i.lines.length>50){for(;i.lines.length>50;){var a=i.lines.splice(i.lines.length-25,25),s=new Di(a);i.height-=s.height;this.children.splice(r+1,0,s);s.parent=this}this.maybeSpill()}break}t-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var t=this;do{var e=t.children.splice(t.children.length-5,5),n=new Li(e);if(t.parent){t.size-=n.size;t.height-=n.height;var r=go(t.parent.children,t);t.parent.children.splice(r+1,0,n)}else{var i=new Li(t.children);i.parent=t;t.children=[i,n];t=i}n.parent=t.parent}while(t.children.length>10);t.parent.maybeSpill()}},iterN:function(t,e,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>t){var a=Math.min(e,o-t);if(i.iterN(t,a,n))return!0;if(0==(e-=a))break;t=0}else t-=o}}};var ns=0,rs=t.Doc=function(t,e,n){if(!(this instanceof rs))return new rs(t,e,n);null==n&&(n=0);Li.call(this,[new Di([new Qa("",null)])]);this.first=n;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=n;var r=ya(n,0);this.sel=J(r);this.history=new Wi(null);this.id=++ns;this.modeOption=e;"string"==typeof t&&(t=Es(t));Mi(this,{from:r,to:r,text:t});ue(this,J(r),gs)};rs.prototype=vo(Li.prototype,{constructor:rs,iter:function(t,e,n){n?this.iterN(t-this.first,e-t,n):this.iterN(this.first,this.first+this.size,t)},insert:function(t,e){for(var n=0,r=0;r<e.length;++r)n+=e[r].height;this.insertInner(t-this.first,e,n)},remove:function(t,e){this.removeInner(t-this.first,e)},getValue:function(t){var e=Ii(this,this.first,this.first+this.size);return t===!1?e:e.join(t||"\n")},setValue:fn(function(t){var e=ya(this.first,0),n=this.first+this.size-1;sr(this,{from:e,to:ya(n,Ei(this,n).text.length),text:Es(t),origin:"setValue"},!0);ue(this,J(e))}),replaceRange:function(t,e,n,r){e=Z(this,e);n=n?Z(this,n):e;dr(this,t,e,n,r)},getRange:function(t,e,n){var r=ji(this,Z(this,t),Z(this,e));return n===!1?r:r.join(n||"\n")},getLine:function(t){var e=this.getLineHandle(t);return e&&e.text },getLineHandle:function(t){return te(this,t)?Ei(this,t):void 0},getLineNumber:function(t){return Hi(t)},getLineHandleVisualStart:function(t){"number"==typeof t&&(t=Ei(this,t));return Qr(t)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(t){return Z(this,t)},getCursor:function(t){var e,n=this.sel.primary();e=null==t||"head"==t?n.head:"anchor"==t?n.anchor:"end"==t||"to"==t||t===!1?n.to():n.from();return e},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:fn(function(t,e,n){ae(this,Z(this,"number"==typeof t?ya(t,e||0):t),null,n)}),setSelection:fn(function(t,e,n){ae(this,Z(this,t),Z(this,e||t),n)}),extendSelection:fn(function(t,e,n){re(this,Z(this,t),e&&Z(this,e),n)}),extendSelections:fn(function(t,e){ie(this,ee(this,t,e))}),extendSelectionsBy:fn(function(t,e){ie(this,mo(this.sel.ranges,t),e)}),setSelections:fn(function(t,e,n){if(t.length){for(var r=0,i=[];r<t.length;r++)i[r]=new $(Z(this,t[r].anchor),Z(this,t[r].head));null==e&&(e=Math.min(t.length-1,this.sel.primIndex));ue(this,Y(i,e),n)}}),addSelection:fn(function(t,e,n){var r=this.sel.ranges.slice(0);r.push(new $(Z(this,t),Z(this,e||t)));ue(this,Y(r,r.length-1),n)}),getSelection:function(t){for(var e,n=this.sel.ranges,r=0;r<n.length;r++){var i=ji(this,n[r].from(),n[r].to());e=e?e.concat(i):i}return t===!1?e:e.join(t||"\n")},getSelections:function(t){for(var e=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=ji(this,n[r].from(),n[r].to());t!==!1&&(i=i.join(t||"\n"));e[r]=i}return e},replaceSelection:function(t,e,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=t;this.replaceSelections(r,e,n||"+input")},replaceSelections:fn(function(t,e,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var a=i.ranges[o];r[o]={from:a.from(),to:a.to(),text:Es(t[o]),origin:n}}for(var s=e&&"end"!=e&&or(this,r,e),o=r.length-1;o>=0;o--)sr(this,r[o]);s?le(this,s):this.cm&&br(this.cm)}),undo:fn(function(){ur(this,"undo")}),redo:fn(function(){ur(this,"redo")}),undoSelection:fn(function(){ur(this,"undo",!0)}),redoSelection:fn(function(){ur(this,"redo",!0)}),setExtending:function(t){this.extend=t},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,n=0,r=0;r<t.done.length;r++)t.done[r].ranges||++e;for(var r=0;r<t.undone.length;r++)t.undone[r].ranges||++n;return{undo:e,redo:n}},clearHistory:function(){this.history=new Wi(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(t){t&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(t){return this.history.generation==(t||this.cleanGeneration)},getHistory:function(){return{done:Ki(this.history.done),undone:Ki(this.history.undone)}},setHistory:function(t){var e=this.history=new Wi(this.history.maxGeneration);e.done=Ki(t.done.slice(0),null,!0);e.undone=Ki(t.undone.slice(0),null,!0)},addLineClass:fn(function(t,e,n){return Cr(this,t,"gutter"==e?"gutter":"class",function(t){var r="text"==e?"textClass":"background"==e?"bgClass":"gutter"==e?"gutterClass":"wrapClass";if(t[r]){if(Do(n).test(t[r]))return!1;t[r]+=" "+n}else t[r]=n;return!0})}),removeLineClass:fn(function(t,e,n){return Cr(this,t,"class",function(t){var r="text"==e?"textClass":"background"==e?"bgClass":"gutter"==e?"gutterClass":"wrapClass",i=t[r];if(!i)return!1;if(null==n)t[r]=null;else{var o=i.match(Do(n));if(!o)return!1;var a=o.index+o[0].length;t[r]=i.slice(0,o.index)+(o.index&&a!=i.length?" ":"")+i.slice(a)||null}return!0})}),markText:function(t,e,n){return Lr(this,Z(this,t),Z(this,e),n,"range")},setBookmark:function(t,e){var n={replacedWith:e&&(null==e.nodeType?e.widget:e),insertLeft:e&&e.insertLeft,clearWhenEmpty:!1,shared:e&&e.shared};t=Z(this,t);return Lr(this,t,t,n,"bookmark")},findMarksAt:function(t){t=Z(this,t);var e=[],n=Ei(this,t.line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=t.ch)&&(null==i.to||i.to>=t.ch)&&e.push(i.marker.parent||i.marker)}return e},findMarks:function(t,e,n){t=Z(this,t);e=Z(this,e);var r=[],i=t.line;this.iter(t.line,e.line+1,function(o){var a=o.markedSpans;if(a)for(var s=0;s<a.length;s++){var l=a[s];i==t.line&&t.ch>l.to||null==l.from&&i!=t.line||i==e.line&&l.from>e.ch||n&&!n(l.marker)||r.push(l.marker.parent||l.marker)}++i});return r},getAllMarks:function(){var t=[];this.iter(function(e){var n=e.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&t.push(n[r].marker)});return t},posFromIndex:function(t){var e,n=this.first;this.iter(function(r){var i=r.text.length+1;if(i>t){e=t;return!0}t-=i;++n});return Z(this,ya(n,e))},indexFromPos:function(t){t=Z(this,t);var e=t.ch;if(t.line<this.first||t.ch<0)return 0;this.iter(this.first,t.line,function(t){e+=t.text.length+1});return e},copy:function(t){var e=new rs(Ii(this,this.first,this.first+this.size),this.modeOption,this.first);e.scrollTop=this.scrollTop;e.scrollLeft=this.scrollLeft;e.sel=this.sel;e.extend=!1;if(t){e.history.undoDepth=this.history.undoDepth;e.setHistory(this.getHistory())}return e},linkedDoc:function(t){t||(t={});var e=this.first,n=this.first+this.size;null!=t.from&&t.from>e&&(e=t.from);null!=t.to&&t.to<n&&(n=t.to);var r=new rs(Ii(this,e,n),t.mode||this.modeOption,e);t.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:t.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:t.sharedHist}];Er(r,Nr(this));return r},unlinkDoc:function(e){e instanceof t&&(e=e.doc);if(this.linked)for(var n=0;n<this.linked.length;++n){var r=this.linked[n];if(r.doc==e){this.linked.splice(n,1);e.unlinkDoc(this);jr(Nr(this));break}}if(e.history==this.history){var i=[e.id];Ai(e,function(t){i.push(t.id)},!0);e.history=new Wi(null);e.history.done=Ki(this.history.done,i);e.history.undone=Ki(this.history.undone,i)}},iterLinkedDocs:function(t){Ai(this,t)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});rs.prototype.eachLine=rs.prototype.iter;var is="iter insert remove copy getEditor".split(" ");for(var os in rs.prototype)rs.prototype.hasOwnProperty(os)&&go(is,os)<0&&(t.prototype[os]=function(t){return function(){return t.apply(this.doc,arguments)}}(rs.prototype[os]));uo(rs);var as=t.e_preventDefault=function(t){t.preventDefault?t.preventDefault():t.returnValue=!1},ss=t.e_stopPropagation=function(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0},ls=t.e_stop=function(t){as(t);ss(t)},us=t.on=function(t,e,n){if(t.addEventListener)t.addEventListener(e,n,!1);else if(t.attachEvent)t.attachEvent("on"+e,n);else{var r=t._handlers||(t._handlers={}),i=r[e]||(r[e]=[]);i.push(n)}},cs=t.off=function(t,e,n){if(t.removeEventListener)t.removeEventListener(e,n,!1);else if(t.detachEvent)t.detachEvent("on"+e,n);else{var r=t._handlers&&t._handlers[e];if(!r)return;for(var i=0;i<r.length;++i)if(r[i]==n){r.splice(i,1);break}}},fs=t.signal=function(t,e){var n=t._handlers&&t._handlers[e];if(n)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)},hs=null,ds=30,ps=t.Pass={toString:function(){return"CodeMirror.Pass"}},gs={scroll:!1},ms={origin:"*mouse"},vs={origin:"+move"};co.prototype.set=function(t,e){clearTimeout(this.id);this.id=setTimeout(e,t)};var ys=t.countColumn=function(t,e,n,r,i){if(null==e){e=t.search(/[^\s\u00a0]/);-1==e&&(e=t.length)}for(var o=r||0,a=i||0;;){var s=t.indexOf(" ",o);if(0>s||s>=e)return a+(e-o);a+=s-o;a+=n-a%n;o=s+1}},bs=[""],xs=function(t){t.select()};ua?xs=function(t){t.selectionStart=0;t.selectionEnd=t.value.length}:Qo&&(xs=function(t){try{t.select()}catch(e){}});[].indexOf&&(go=function(t,e){return t.indexOf(e)});[].map&&(mo=function(t,e){return t.map(e)});var ws,Cs=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Ss=t.isWordChar=function(t){return/\w/.test(t)||t>"€"&&(t.toUpperCase()!=t.toLowerCase()||Cs.test(t))},Ts=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ws=document.createRange?function(t,e,n){var r=document.createRange();r.setEnd(t,n);r.setStart(t,e);return r}:function(t,e,n){var r=document.body.createTextRange();try{r.moveToElementText(t.parentNode)}catch(i){return r}r.collapse(!0);r.moveEnd("character",n);r.moveStart("character",e);return r};Qo&&11>ta&&(Mo=function(){try{return document.activeElement}catch(t){return document.body}});var ks,_s,Ms,Ds=t.rmClass=function(t,e){var n=t.className,r=Do(e).exec(n);if(r){var i=n.slice(r.index+r[0].length);t.className=n.slice(0,r.index)+(i?r[1]+i:"")}},Ls=t.addClass=function(t,e){var n=t.className;Do(e).test(n)||(t.className+=(n?" ":"")+e)},As=!1,Ns=function(){if(Qo&&9>ta)return!1;var t=So("div");return"draggable"in t||"dragDrop"in t}(),Es=t.splitLines=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,n=[],r=t.length;r>=e;){var i=t.indexOf("\n",e);-1==i&&(i=t.length);var o=t.slice(e,"\r"==t.charAt(i-1)?i-1:i),a=o.indexOf("\r");if(-1!=a){n.push(o.slice(0,a));e+=a+1}else{n.push(o);e=i+1}}return n}:function(t){return t.split(/\r\n?|\n/)},js=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(e){return!1}}:function(t){try{var e=t.ownerDocument.selection.createRange()}catch(n){}return e&&e.parentElement()==t?0!=e.compareEndPoints("StartToEnd",e):!1},Is=function(){var t=So("div");if("oncopy"in t)return!0;t.setAttribute("oncopy","return;");return"function"==typeof t.oncopy}(),Ps=null,Hs={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};t.keyNames=Hs;(function(){for(var t=0;10>t;t++)Hs[t+48]=Hs[t+96]=String(t);for(var t=65;90>=t;t++)Hs[t]=String.fromCharCode(t);for(var t=1;12>=t;t++)Hs[t+111]=Hs[t+63235]="F"+t})();var Os,Fs=function(){function t(t){return 247>=t?n.charAt(t):t>=1424&&1524>=t?"R":t>=1536&&1773>=t?r.charAt(t-1536):t>=1774&&2220>=t?"r":t>=8192&&8203>=t?"w":8204==t?"b":"L"}function e(t,e,n){this.level=t;this.from=e;this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,a=/[LRr]/,s=/[Lb1n]/,l=/[1n]/,u="L";return function(n){if(!i.test(n))return!1;for(var r,c=n.length,f=[],h=0;c>h;++h)f.push(r=t(n.charCodeAt(h)));for(var h=0,d=u;c>h;++h){var r=f[h];"m"==r?f[h]=d:d=r}for(var h=0,p=u;c>h;++h){var r=f[h];if("1"==r&&"r"==p)f[h]="n";else if(a.test(r)){p=r;"r"==r&&(f[h]="R")}}for(var h=1,d=f[0];c-1>h;++h){var r=f[h];"+"==r&&"1"==d&&"1"==f[h+1]?f[h]="1":","!=r||d!=f[h+1]||"1"!=d&&"n"!=d||(f[h]=d);d=r}for(var h=0;c>h;++h){var r=f[h];if(","==r)f[h]="N";else if("%"==r){for(var g=h+1;c>g&&"%"==f[g];++g);for(var m=h&&"!"==f[h-1]||c>g&&"1"==f[g]?"1":"N",v=h;g>v;++v)f[v]=m;h=g-1}}for(var h=0,p=u;c>h;++h){var r=f[h];"L"==p&&"1"==r?f[h]="L":a.test(r)&&(p=r)}for(var h=0;c>h;++h)if(o.test(f[h])){for(var g=h+1;c>g&&o.test(f[g]);++g);for(var y="L"==(h?f[h-1]:u),b="L"==(c>g?f[g]:u),m=y||b?"L":"R",v=h;g>v;++v)f[v]=m;h=g-1}for(var x,w=[],h=0;c>h;)if(s.test(f[h])){var C=h;for(++h;c>h&&s.test(f[h]);++h);w.push(new e(0,C,h))}else{var S=h,T=w.length;for(++h;c>h&&"L"!=f[h];++h);for(var v=S;h>v;)if(l.test(f[v])){v>S&&w.splice(T,0,new e(1,S,v));var k=v;for(++v;h>v&&l.test(f[v]);++v);w.splice(T,0,new e(2,k,v));S=v}else++v;h>S&&w.splice(T,0,new e(1,S,h))}if(1==w[0].level&&(x=n.match(/^\s+/))){w[0].from=x[0].length;w.unshift(new e(0,0,x[0].length))}if(1==po(w).level&&(x=n.match(/\s+$/))){po(w).to-=x[0].length;w.push(new e(0,c-x[0].length,c))}w[0].level!=po(w).level&&w.push(new e(w[0].level,c,c));return w}}();t.version="4.8.0";return t})},{}],11:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.defineMode("javascript",function(e,n){function r(t){for(var e,n=!1,r=!1;null!=(e=t.next());){if(!n){if("/"==e&&!r)return;"["==e?r=!0:r&&"]"==e&&(r=!1)}n=!n&&"\\"==e}}function i(t,e,n){pe=t;ge=n;return e}function o(t,e){var n=t.next();if('"'==n||"'"==n){e.tokenize=a(n);return e.tokenize(t,e)}if("."==n&&t.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&t.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&t.eat(">"))return i("=>","operator");if("0"==n&&t.eat(/x/i)){t.eatWhile(/[\da-f]/i);return i("number","number")}if(/\d/.test(n)){t.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return i("number","number")}if("/"==n){if(t.eat("*")){e.tokenize=s;return s(t,e)}if(t.eat("/")){t.skipToEnd();return i("comment","comment")}if("operator"==e.lastType||"keyword c"==e.lastType||"sof"==e.lastType||/^[\[{}\(,;:]$/.test(e.lastType)){r(t);t.eatWhile(/[gimy]/);return i("regexp","string-2")}t.eatWhile(Se);return i("operator","operator",t.current())}if("`"==n){e.tokenize=l;return l(t,e)}if("#"==n){t.skipToEnd();return i("error","error")}if(Se.test(n)){t.eatWhile(Se);return i("operator","operator",t.current())}if(we.test(n)){t.eatWhile(we);var o=t.current(),u=Ce.propertyIsEnumerable(o)&&Ce[o];return u&&"."!=e.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function a(t){return function(e,n){var r,a=!1;if(ye&&"@"==e.peek()&&e.match(Te)){n.tokenize=o;return i("jsonld-keyword","meta")}for(;null!=(r=e.next())&&(r!=t||a);)a=!a&&"\\"==r;a||(n.tokenize=o);return i("string","string")}}function s(t,e){for(var n,r=!1;n=t.next();){if("/"==n&&r){e.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(t,e){for(var n,r=!1;null!=(n=t.next());){if(!r&&("`"==n||"$"==n&&t.eat("{"))){e.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",t.current())}function u(t,e){e.fatArrowAt&&(e.fatArrowAt=null);var n=t.string.indexOf("=>",t.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var a=t.string.charAt(o),s=ke.indexOf(a);if(s>=0&&3>s){if(!r){++o;break}if(0==--r)break}else if(s>=3&&6>s)++r;else if(we.test(a))i=!0;else if(i&&!r){++o;break}}i&&!r&&(e.fatArrowAt=o)}}function c(t,e,n,r,i,o){this.indented=t;this.column=e;this.type=n;this.prev=i;this.info=o;null!=r&&(this.align=r)}function f(t,e){for(var n=t.localVars;n;n=n.next)if(n.name==e)return!0;for(var r=t.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==e)return!0}function h(t,e,n,r,i){var o=t.cc;Me.state=t;Me.stream=i;Me.marked=null,Me.cc=o;Me.style=e;t.lexical.hasOwnProperty("align")||(t.lexical.align=!0);for(;;){var a=o.length?o.pop():be?C:w;if(a(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Me.marked?Me.marked:"variable"==n&&f(t,r)?"variable-2":e}}}function d(){for(var t=arguments.length-1;t>=0;t--)Me.cc.push(arguments[t])}function p(){d.apply(null,arguments);return!0}function g(t){function e(e){for(var n=e;n;n=n.next)if(n.name==t)return!0;return!1}var r=Me.state;if(r.context){Me.marked="def";if(e(r.localVars))return;r.localVars={name:t,next:r.localVars}}else{if(e(r.globalVars))return;n.globalVars&&(r.globalVars={name:t,next:r.globalVars})}}function m(){Me.state.context={prev:Me.state.context,vars:Me.state.localVars};Me.state.localVars=De}function v(){Me.state.localVars=Me.state.context.vars;Me.state.context=Me.state.context.prev}function y(t,e){var n=function(){var n=Me.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new c(r,Me.stream.column(),t,null,n.lexical,e)};n.lex=!0;return n}function b(){var t=Me.state;if(t.lexical.prev){")"==t.lexical.type&&(t.indented=t.lexical.indented);t.lexical=t.lexical.prev}}function x(t){function e(n){return n==t?p():";"==t?d():p(e)}return e}function w(t,e){if("var"==t)return p(y("vardef",e.length),U,x(";"),b);if("keyword a"==t)return p(y("form"),C,w,b);if("keyword b"==t)return p(y("form"),w,b);if("{"==t)return p(y("}"),W,b);if(";"==t)return p();if("if"==t){"else"==Me.state.lexical.info&&Me.state.cc[Me.state.cc.length-1]==b&&Me.state.cc.pop()();return p(y("form"),C,w,b,$)}return"function"==t?p(te):"for"==t?p(y("form"),Y,w,b):"variable"==t?p(y("stat"),j):"switch"==t?p(y("form"),C,y("}","switch"),x("{"),W,b,b):"case"==t?p(C,x(":")):"default"==t?p(x(":")):"catch"==t?p(y("form"),m,x("("),ee,x(")"),w,b,v):"module"==t?p(y("form"),m,ae,v,b):"class"==t?p(y("form"),ne,b):"export"==t?p(y("form"),se,b):"import"==t?p(y("form"),le,b):d(y("stat"),C,x(";"),b)}function C(t){return T(t,!1)}function S(t){return T(t,!0)}function T(t,e){if(Me.state.fatArrowAt==Me.stream.start){var n=e?E:N;if("("==t)return p(m,y(")"),F(B,")"),b,x("=>"),n,v);if("variable"==t)return d(m,B,x("=>"),n,v)}var r=e?D:M;return _e.hasOwnProperty(t)?p(r):"function"==t?p(te,r):"keyword c"==t?p(e?_:k):"("==t?p(y(")"),k,de,x(")"),b,r):"operator"==t||"spread"==t?p(e?S:C):"["==t?p(y("]"),fe,b,r):"{"==t?R(P,"}",null,r):"quasi"==t?d(L,r):p()}function k(t){return t.match(/[;\}\)\],]/)?d():d(C)}function _(t){return t.match(/[;\}\)\],]/)?d():d(S)}function M(t,e){return","==t?p(C):D(t,e,!1)}function D(t,e,n){var r=0==n?M:D,i=0==n?C:S;return"=>"==t?p(m,n?E:N,v):"operator"==t?/\+\+|--/.test(e)?p(r):"?"==e?p(C,x(":"),i):p(i):"quasi"==t?d(L,r):";"!=t?"("==t?R(S,")","call",r):"."==t?p(I,r):"["==t?p(y("]"),k,x("]"),b,r):void 0:void 0}function L(t,e){return"quasi"!=t?d():"${"!=e.slice(e.length-2)?p(L):p(C,A)}function A(t){if("}"==t){Me.marked="string-2";Me.state.tokenize=l;return p(L)}}function N(t){u(Me.stream,Me.state);return d("{"==t?w:C)}function E(t){u(Me.stream,Me.state);return d("{"==t?w:S)}function j(t){return":"==t?p(b,w):d(M,x(";"),b)}function I(t){if("variable"==t){Me.marked="property";return p()}}function P(t,e){if("variable"==t||"keyword"==Me.style){Me.marked="property";return p("get"==e||"set"==e?H:O)}if("number"==t||"string"==t){Me.marked=ye?"property":Me.style+" property";return p(O)}return"jsonld-keyword"==t?p(O):"["==t?p(C,x("]"),O):void 0}function H(t){if("variable"!=t)return d(O);Me.marked="property";return p(te)}function O(t){return":"==t?p(S):"("==t?d(te):void 0}function F(t,e){function n(r){if(","==r){var i=Me.state.lexical;"call"==i.info&&(i.pos=(i.pos||0)+1);return p(t,n)}return r==e?p():p(x(e))}return function(r){return r==e?p():d(t,n)}}function R(t,e,n){for(var r=3;r<arguments.length;r++)Me.cc.push(arguments[r]);return p(y(e,n),F(t,e),b)}function W(t){return"}"==t?p():d(w,W)}function z(t){return xe&&":"==t?p(q):void 0}function q(t){if("variable"==t){Me.marked="variable-3";return p()}}function U(){return d(B,z,X,G)}function B(t,e){if("variable"==t){g(e);return p()}return"["==t?R(B,"]"):"{"==t?R(V,"}"):void 0}function V(t,e){if("variable"==t&&!Me.stream.match(/^\s*:/,!1)){g(e);return p(X)}"variable"==t&&(Me.marked="property");return p(x(":"),B,X)}function X(t,e){return"="==e?p(S):void 0}function G(t){return","==t?p(U):void 0}function $(t,e){return"keyword b"==t&&"else"==e?p(y("form","else"),w,b):void 0}function Y(t){return"("==t?p(y(")"),J,x(")"),b):void 0}function J(t){return"var"==t?p(U,x(";"),Z):";"==t?p(Z):"variable"==t?p(K):d(C,x(";"),Z)}function K(t,e){if("in"==e||"of"==e){Me.marked="keyword";return p(C)}return p(M,Z)}function Z(t,e){if(";"==t)return p(Q);if("in"==e||"of"==e){Me.marked="keyword";return p(C)}return d(C,x(";"),Q)}function Q(t){")"!=t&&p(C)}function te(t,e){if("*"==e){Me.marked="keyword";return p(te)}if("variable"==t){g(e);return p(te)}return"("==t?p(m,y(")"),F(ee,")"),b,w,v):void 0}function ee(t){return"spread"==t?p(ee):d(B,z)}function ne(t,e){if("variable"==t){g(e);return p(re)}}function re(t,e){return"extends"==e?p(C,re):"{"==t?p(y("}"),ie,b):void 0}function ie(t,e){if("variable"==t||"keyword"==Me.style){Me.marked="property";return"get"==e||"set"==e?p(oe,te,ie):p(te,ie)}if("*"==e){Me.marked="keyword";return p(ie)}return";"==t?p(ie):"}"==t?p():void 0}function oe(t){if("variable"!=t)return d();Me.marked="property";return p()}function ae(t,e){if("string"==t)return p(w);if("variable"==t){g(e);return p(ce)}}function se(t,e){if("*"==e){Me.marked="keyword";return p(ce,x(";"))}if("default"==e){Me.marked="keyword";return p(C,x(";"))}return d(w)}function le(t){return"string"==t?p():d(ue,ce)}function ue(t,e){if("{"==t)return R(ue,"}");"variable"==t&&g(e);return p()}function ce(t,e){if("from"==e){Me.marked="keyword";return p(C)}}function fe(t){return"]"==t?p():d(S,he)}function he(t){return"for"==t?d(de,x("]")):","==t?p(F(_,"]")):d(F(S,"]"))}function de(t){return"for"==t?p(Y,de):"if"==t?p(C,de):void 0}var pe,ge,me=e.indentUnit,ve=n.statementIndent,ye=n.jsonld,be=n.json||ye,xe=n.typescript,we=n.wordCharacters||/[\w$\xa1-\uffff]/,Ce=function(){function t(t){return{type:t,style:"keyword"}}var e=t("keyword a"),n=t("keyword b"),r=t("keyword c"),i=t("operator"),o={type:"atom",style:"atom"},a={"if":t("if"),"while":e,"with":e,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":t("var"),"const":t("var"),let:t("var"),"function":t("function"),"catch":t("catch"),"for":t("for"),"switch":t("switch"),"case":t("case"),"default":t("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":t("this"),module:t("module"),"class":t("class"),"super":t("atom"),"yield":r,"export":t("export"),"import":t("import"),"extends":r};if(xe){var s={type:"variable",style:"variable-3"},l={"interface":t("interface"),"extends":t("extends"),constructor:t("constructor"),"public":t("public"),"private":t("private"),"protected":t("protected"),"static":t("static"),string:s,number:s,bool:s,any:s};for(var u in l)a[u]=l[u]}return a}(),Se=/[+\-*&%=<>!?|~^]/,Te=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,ke="([{}])",_e={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Me={state:null,column:null,marked:null,cc:null},De={name:"this",next:{name:"arguments"}};b.lex=!0;return{startState:function(t){var e={tokenize:o,lastType:"sof",cc:[],lexical:new c((t||0)-me,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};n.globalVars&&"object"==typeof n.globalVars&&(e.globalVars=n.globalVars);return e},token:function(t,e){if(t.sol()){e.lexical.hasOwnProperty("align")||(e.lexical.align=!1);e.indented=t.indentation();u(t,e)}if(e.tokenize!=s&&t.eatSpace())return null;var n=e.tokenize(t,e);if("comment"==pe)return n;e.lastType="operator"!=pe||"++"!=ge&&"--"!=ge?pe:"incdec";return h(e,n,pe,ge,t)},indent:function(e,r){if(e.tokenize==s)return t.Pass;if(e.tokenize!=o)return 0;var i=r&&r.charAt(0),a=e.lexical;if(!/^\s*else\b/.test(r))for(var l=e.cc.length-1;l>=0;--l){var u=e.cc[l];if(u==b)a=a.prev;else if(u!=$)break}"stat"==a.type&&"}"==i&&(a=a.prev);ve&&")"==a.type&&"stat"==a.prev.type&&(a=a.prev);var c=a.type,f=i==c;return"vardef"==c?a.indented+("operator"==e.lastType||","==e.lastType?a.info+1:0):"form"==c&&"{"==i?a.indented:"form"==c?a.indented+me:"stat"==c?a.indented+("operator"==e.lastType||","==e.lastType?ve||me:0):"switch"!=a.info||f||0==n.doubleIndentSwitch?a.align?a.column+(f?0:1):a.indented+(f?0:me):a.indented+(/^(?:case|default)\b/.test(r)?me:2*me)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:be?null:"/*",blockCommentEnd:be?null:"*/",lineComment:be?null:"//",fold:"brace",helperType:be?"json":"javascript",jsonldMode:ye,jsonMode:be}});t.registerHelper("wordChars","javascript",/[\w$]/);t.defineMIME("text/javascript","javascript");t.defineMIME("text/ecmascript","javascript");t.defineMIME("application/javascript","javascript");t.defineMIME("application/x-javascript","javascript");t.defineMIME("application/ecmascript","javascript");t.defineMIME("application/json",{name:"javascript",json:!0});t.defineMIME("application/x-json",{name:"javascript",json:!0});t.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});t.defineMIME("text/typescript",{name:"javascript",typescript:!0});t.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{"../../lib/codemirror":10}],12:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.defineMode("xml",function(e,n){function r(t,e){function n(n){e.tokenize=n;return n(t,e)}var r=t.next();if("<"==r){if(t.eat("!")){if(t.eat("["))return t.match("CDATA[")?n(a("atom","]]>")):null;if(t.match("--"))return n(a("comment","-->"));if(t.match("DOCTYPE",!0,!0)){t.eatWhile(/[\w\._\-]/);return n(s(1))}return null}if(t.eat("?")){t.eatWhile(/[\w\._\-]/);e.tokenize=a("meta","?>");return"meta"}S=t.eat("/")?"closeTag":"openTag";e.tokenize=i;return"tag bracket"}if("&"==r){var o;o=t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";");return o?"atom":"error"}t.eatWhile(/[^&<]/);return null}function i(t,e){var n=t.next();if(">"==n||"/"==n&&t.eat(">")){e.tokenize=r;S=">"==n?"endTag":"selfcloseTag";return"tag bracket"}if("="==n){S="equals";return null}if("<"==n){e.tokenize=r;e.state=f;e.tagName=e.tagStart=null;var i=e.tokenize(t,e);return i?i+" tag error":"tag error"}if(/[\'\"]/.test(n)){e.tokenize=o(n);e.stringStartCol=t.column();return e.tokenize(t,e)}t.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word"}function o(t){var e=function(e,n){for(;!e.eol();)if(e.next()==t){n.tokenize=i;break}return"string"};e.isInAttribute=!0;return e}function a(t,e){return function(n,i){for(;!n.eol();){if(n.match(e)){i.tokenize=r;break}n.next()}return t}}function s(t){return function(e,n){for(var i;null!=(i=e.next());){if("<"==i){n.tokenize=s(t+1);return n.tokenize(e,n)}if(">"==i){if(1==t){n.tokenize=r;break}n.tokenize=s(t-1);return n.tokenize(e,n)}}return"meta"}}function l(t,e,n){this.prev=t.context;this.tagName=e;this.indent=t.indented;this.startOfLine=n;(k.doNotIndent.hasOwnProperty(e)||t.context&&t.context.noIndent)&&(this.noIndent=!0)}function u(t){t.context&&(t.context=t.context.prev)}function c(t,e){for(var n;;){if(!t.context)return;n=t.context.tagName;if(!k.contextGrabbers.hasOwnProperty(n)||!k.contextGrabbers[n].hasOwnProperty(e))return;u(t)}}function f(t,e,n){if("openTag"==t){n.tagStart=e.column();return h}return"closeTag"==t?d:f}function h(t,e,n){if("word"==t){n.tagName=e.current();T="tag";return m}T="error";return h}function d(t,e,n){if("word"==t){var r=e.current();n.context&&n.context.tagName!=r&&k.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n);if(n.context&&n.context.tagName==r){T="tag";return p}T="tag error";return g}T="error";return g}function p(t,e,n){if("endTag"!=t){T="error";return p}u(n);return f}function g(t,e,n){T="error";return p(t,e,n)}function m(t,e,n){if("word"==t){T="attribute";return v}if("endTag"==t||"selfcloseTag"==t){var r=n.tagName,i=n.tagStart;n.tagName=n.tagStart=null;if("selfcloseTag"==t||k.autoSelfClosers.hasOwnProperty(r))c(n,r);else{c(n,r);n.context=new l(n,r,i==n.indented)}return f}T="error";return m}function v(t,e,n){if("equals"==t)return y;k.allowMissing||(T="error");return m(t,e,n)}function y(t,e,n){if("string"==t)return b;if("word"==t&&k.allowUnquoted){T="string";return m}T="error";return m(t,e,n)}function b(t,e,n){return"string"==t?b:m(t,e,n)}var x=e.indentUnit,w=n.multilineTagIndentFactor||1,C=n.multilineTagIndentPastTag;null==C&&(C=!0);var S,T,k=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},_=n.alignCDATA;return{startState:function(){return{tokenize:r,state:f,indented:0,tagName:null,tagStart:null,context:null}},token:function(t,e){!e.tagName&&t.sol()&&(e.indented=t.indentation());if(t.eatSpace())return null;S=null;var n=e.tokenize(t,e);if((n||S)&&"comment"!=n){T=null;e.state=e.state(S||n,t,e);T&&(n="error"==T?n+" error":T)}return n},indent:function(e,n,o){var a=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+x;if(a&&a.noIndent)return t.Pass;if(e.tokenize!=i&&e.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(e.tagName)return C?e.tagStart+e.tagName.length+2:e.tagStart+x*w;if(_&&/<!\[CDATA\[/.test(n))return 0;var s=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(s&&s[1])for(;a;){if(a.tagName==s[2]){a=a.prev;break}if(!k.implicitlyClosed.hasOwnProperty(a.tagName))break;a=a.prev}else if(s)for(;a;){var l=k.contextGrabbers[a.tagName];if(!l||!l.hasOwnProperty(s[2]))break;a=a.prev}for(;a&&!a.startOfLine;)a=a.prev;return a?a.indent+x:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"} });t.defineMIME("text/xml","xml");t.defineMIME("application/xml","xml");t.mimeModes.hasOwnProperty("text/html")||t.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{"../../lib/codemirror":10}],13:[function(e,n){!function(){function e(t,e){return e>t?-1:t>e?1:t>=e?0:0/0}function r(t){return null===t?0/0:+t}function i(t){return!isNaN(t)}function o(t){return{left:function(e,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=e.length);for(;i>r;){var o=r+i>>>1;t(e[o],n)<0?r=o+1:i=o}return r},right:function(e,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=e.length);for(;i>r;){var o=r+i>>>1;t(e[o],n)>0?i=o:r=o+1}return r}}}function a(t){return t.length}function s(t){for(var e=1;t*e%1;)e*=10;return e}function l(t,e){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],enumerable:!1})}function u(){this._=Object.create(null)}function c(t){return(t+="")===bs||t[0]===xs?xs+t:t}function f(t){return(t+="")[0]===xs?t.slice(1):t}function h(t){return c(t)in this._}function d(t){return(t=c(t))in this._&&delete this._[t]}function p(){var t=[];for(var e in this._)t.push(f(e));return t}function g(){var t=0;for(var e in this._)++t;return t}function m(){for(var t in this._)return!1;return!0}function v(){this._=Object.create(null)}function y(t,e,n){return function(){var r=n.apply(e,arguments);return r===e?t:r}}function b(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var n=0,r=ws.length;r>n;++n){var i=ws[n]+e;if(i in t)return i}}function x(){}function w(){}function C(t){function e(){for(var e,r=n,i=-1,o=r.length;++i<o;)(e=r[i].on)&&e.apply(this,arguments);return t}var n=[],r=new u;e.on=function(e,i){var o,a=r.get(e);if(arguments.length<2)return a&&a.on;if(a){a.on=null;n=n.slice(0,o=n.indexOf(a)).concat(n.slice(o+1));r.remove(e)}i&&n.push(r.set(e,{on:i}));return t};return e}function S(){is.event.preventDefault()}function T(){for(var t,e=is.event;t=e.sourceEvent;)e=t;return e}function k(t){for(var e=new w,n=0,r=arguments.length;++n<r;)e[arguments[n]]=C(e);e.of=function(n,r){return function(i){try{var o=i.sourceEvent=is.event;i.target=t;is.event=i;e[i.type].apply(n,r)}finally{is.event=o}}};return e}function _(t){Ss(t,Ds);return t}function M(t){return"function"==typeof t?t:function(){return Ts(t,this)}}function D(t){return"function"==typeof t?t:function(){return ks(t,this)}}function L(t,e){function n(){this.removeAttribute(t)}function r(){this.removeAttributeNS(t.space,t.local)}function i(){this.setAttribute(t,e)}function o(){this.setAttributeNS(t.space,t.local,e)}function a(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}function s(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}t=is.ns.qualify(t);return null==e?t.local?r:n:"function"==typeof e?t.local?s:a:t.local?o:i}function A(t){return t.trim().replace(/\s+/g," ")}function N(t){return new RegExp("(?:^|\\s+)"+is.requote(t)+"(?:\\s+|$)","g")}function E(t){return(t+"").trim().split(/^|\s+/)}function j(t,e){function n(){for(var n=-1;++n<i;)t[n](this,e)}function r(){for(var n=-1,r=e.apply(this,arguments);++n<i;)t[n](this,r)}t=E(t).map(I);var i=t.length;return"function"==typeof e?r:n}function I(t){var e=N(t);return function(n,r){if(i=n.classList)return r?i.add(t):i.remove(t);var i=n.getAttribute("class")||"";if(r){e.lastIndex=0;e.test(i)||n.setAttribute("class",A(i+" "+t))}else n.setAttribute("class",A(i.replace(e," ")))}}function P(t,e,n){function r(){this.style.removeProperty(t)}function i(){this.style.setProperty(t,e,n)}function o(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}return null==e?r:"function"==typeof e?o:i}function H(t,e){function n(){delete this[t]}function r(){this[t]=e}function i(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}return null==e?n:"function"==typeof e?i:r}function O(t){return"function"==typeof t?t:(t=is.ns.qualify(t)).local?function(){return this.ownerDocument.createElementNS(t.space,t.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,t)}}function F(){var t=this.parentNode;t&&t.removeChild(this)}function R(t){return{__data__:t}}function W(t){return function(){return Ms(this,t)}}function z(t){arguments.length||(t=e);return function(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}}function q(t,e){for(var n=0,r=t.length;r>n;n++)for(var i,o=t[n],a=0,s=o.length;s>a;a++)(i=o[a])&&e(i,a,n);return t}function U(t){Ss(t,As);return t}function B(t){var e,n;return function(r,i,o){var a,s=t[o].update,l=s.length;o!=n&&(n=o,e=0);i>=e&&(e=i+1);for(;!(a=s[e])&&++e<l;);return a}}function V(t,e,n){function r(){var e=this[a];if(e){this.removeEventListener(t,e,e.$);delete this[a]}}function i(){var i=l(e,as(arguments));r.call(this);this.addEventListener(t,this[a]=i,i.$=n);i._=e}function o(){var e,n=new RegExp("^__on([^.]+)"+is.requote(t)+"$");for(var r in this)if(e=r.match(n)){var i=this[r];this.removeEventListener(e[1],i,i.$);delete this[r]}}var a="__on"+t,s=t.indexOf("."),l=X;s>0&&(t=t.slice(0,s));var u=Es.get(t);u&&(t=u,l=G);return s?e?i:r:e?x:o}function X(t,e){return function(n){var r=is.event;is.event=n;e[0]=this.__data__;try{t.apply(this,e)}finally{is.event=r}}}function G(t,e){var n=X(t,e);return function(t){var e=this,r=t.relatedTarget;r&&(r===e||8&r.compareDocumentPosition(e))||n.call(e,t)}}function $(){var t=".dragsuppress-"+ ++Is,e="click"+t,n=is.select(us).on("touchmove"+t,S).on("dragstart"+t,S).on("selectstart"+t,S);if(js){var r=ls.style,i=r[js];r[js]="none"}return function(o){n.on(t,null);js&&(r[js]=i);if(o){var a=function(){n.on(e,null)};n.on(e,function(){S();a()},!0);setTimeout(a,0)}}}function Y(t,e){e.changedTouches&&(e=e.changedTouches[0]);var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();if(0>Ps&&(us.scrollX||us.scrollY)){n=is.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var i=n[0][0].getScreenCTM();Ps=!(i.f||i.e);n.remove()}Ps?(r.x=e.pageX,r.y=e.pageY):(r.x=e.clientX,r.y=e.clientY);r=r.matrixTransform(t.getScreenCTM().inverse());return[r.x,r.y]}var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}function J(){return is.event.changedTouches[0].identifier}function K(){return is.event.target}function Z(){return us}function Q(t){return t>0?1:0>t?-1:0}function te(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function ee(t){return t>1?0:-1>t?Fs:Math.acos(t)}function ne(t){return t>1?zs:-1>t?-zs:Math.asin(t)}function re(t){return((t=Math.exp(t))-1/t)/2}function ie(t){return((t=Math.exp(t))+1/t)/2}function oe(t){return((t=Math.exp(2*t))-1)/(t+1)}function ae(t){return(t=Math.sin(t/2))*t}function se(){}function le(t,e,n){return this instanceof le?void(this.h=+t,this.s=+e,this.l=+n):arguments.length<2?t instanceof le?new le(t.h,t.s,t.l):Ce(""+t,Se,le):new le(t,e,n)}function ue(t,e,n){function r(t){t>360?t-=360:0>t&&(t+=360);return 60>t?o+(a-o)*t/60:180>t?a:240>t?o+(a-o)*(240-t)/60:o}function i(t){return Math.round(255*r(t))}var o,a;t=isNaN(t)?0:(t%=360)<0?t+360:t;e=isNaN(e)?0:0>e?0:e>1?1:e;n=0>n?0:n>1?1:n;a=.5>=n?n*(1+e):n+e-n*e;o=2*n-a;return new ye(i(t+120),i(t),i(t-120))}function ce(t,e,n){return this instanceof ce?void(this.h=+t,this.c=+e,this.l=+n):arguments.length<2?t instanceof ce?new ce(t.h,t.c,t.l):t instanceof he?pe(t.l,t.a,t.b):pe((t=Te((t=is.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ce(t,e,n)}function fe(t,e,n){isNaN(t)&&(t=0);isNaN(e)&&(e=0);return new he(n,Math.cos(t*=qs)*e,Math.sin(t)*e)}function he(t,e,n){return this instanceof he?void(this.l=+t,this.a=+e,this.b=+n):arguments.length<2?t instanceof he?new he(t.l,t.a,t.b):t instanceof ce?fe(t.h,t.c,t.l):Te((t=ye(t)).r,t.g,t.b):new he(t,e,n)}function de(t,e,n){var r=(t+16)/116,i=r+e/500,o=r-n/200;i=ge(i)*Qs;r=ge(r)*tl;o=ge(o)*el;return new ye(ve(3.2404542*i-1.5371385*r-.4985314*o),ve(-.969266*i+1.8760108*r+.041556*o),ve(.0556434*i-.2040259*r+1.0572252*o))}function pe(t,e,n){return t>0?new ce(Math.atan2(n,e)*Us,Math.sqrt(e*e+n*n),t):new ce(0/0,0/0,t)}function ge(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function me(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ve(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ye(t,e,n){return this instanceof ye?void(this.r=~~t,this.g=~~e,this.b=~~n):arguments.length<2?t instanceof ye?new ye(t.r,t.g,t.b):Ce(""+t,ye,ue):new ye(t,e,n)}function be(t){return new ye(t>>16,t>>8&255,255&t)}function xe(t){return be(t)+""}function we(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function Ce(t,e,n){var r,i,o,a=0,s=0,l=0;r=/([a-z]+)\((.*)\)/i.exec(t);if(r){i=r[2].split(",");switch(r[1]){case"hsl":return n(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(_e(i[0]),_e(i[1]),_e(i[2]))}}if(o=il.get(t))return e(o.r,o.g,o.b);if(null!=t&&"#"===t.charAt(0)&&!isNaN(o=parseInt(t.slice(1),16)))if(4===t.length){a=(3840&o)>>4;a=a>>4|a;s=240&o;s=s>>4|s;l=15&o;l=l<<4|l}else if(7===t.length){a=(16711680&o)>>16;s=(65280&o)>>8;l=255&o}return e(a,s,l)}function Se(t,e,n){var r,i,o=Math.min(t/=255,e/=255,n/=255),a=Math.max(t,e,n),s=a-o,l=(a+o)/2;if(s){i=.5>l?s/(a+o):s/(2-a-o);r=t==a?(e-n)/s+(n>e?6:0):e==a?(n-t)/s+2:(t-e)/s+4;r*=60}else{r=0/0;i=l>0&&1>l?0:r}return new le(r,i,l)}function Te(t,e,n){t=ke(t);e=ke(e);n=ke(n);var r=me((.4124564*t+.3575761*e+.1804375*n)/Qs),i=me((.2126729*t+.7151522*e+.072175*n)/tl),o=me((.0193339*t+.119192*e+.9503041*n)/el);return he(116*i-16,500*(r-i),200*(i-o))}function ke(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function _e(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Me(t){return"function"==typeof t?t:function(){return t}}function De(t){return t}function Le(t){return function(e,n,r){2===arguments.length&&"function"==typeof n&&(r=n,n=null);return Ae(e,n,t,r)}}function Ae(t,e,n,r){function i(){var t,e=l.status;if(!e&&Ee(l)||e>=200&&300>e||304===e){try{t=n.call(o,l)}catch(r){a.error.call(o,r);return}a.load.call(o,t)}else a.error.call(o,l)}var o={},a=is.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,u=null;!us.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest);"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()};l.onprogress=function(t){var e=is.event;is.event=t;try{a.progress.call(o,l)}finally{is.event=e}};o.header=function(t,e){t=(t+"").toLowerCase();if(arguments.length<2)return s[t];null==e?delete s[t]:s[t]=e+"";return o};o.mimeType=function(t){if(!arguments.length)return e;e=null==t?null:t+"";return o};o.responseType=function(t){if(!arguments.length)return u;u=t;return o};o.response=function(t){n=t;return o};["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(as(arguments)))}});o.send=function(n,r,i){2===arguments.length&&"function"==typeof r&&(i=r,r=null);l.open(n,t,!0);null==e||"accept"in s||(s.accept=e+",*/*");if(l.setRequestHeader)for(var c in s)l.setRequestHeader(c,s[c]);null!=e&&l.overrideMimeType&&l.overrideMimeType(e);null!=u&&(l.responseType=u);null!=i&&o.on("error",i).on("load",function(t){i(null,t)});a.beforesend.call(o,l);l.send(null==r?null:r);return o};o.abort=function(){l.abort();return o};is.rebind(o,a,"on");return null==r?o:o.get(Ne(r))}function Ne(t){return 1===t.length?function(e,n){t(null==e?n:null)}:t}function Ee(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function je(){var t=Ie(),e=Pe()-t;if(e>24){if(isFinite(e)){clearTimeout(ll);ll=setTimeout(je,e)}sl=0}else{sl=1;cl(je)}}function Ie(){var t=Date.now();ul=ol;for(;ul;){t>=ul.t&&(ul.f=ul.c(t-ul.t));ul=ul.n}return t}function Pe(){for(var t,e=ol,n=1/0;e;)if(e.f)e=t?t.n=e.n:ol=e.n;else{e.t<n&&(n=e.t);e=(t=e).n}al=t;return n}function He(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}function Oe(t,e){var n=Math.pow(10,3*ys(8-e));return{scale:e>8?function(t){return t/n}:function(t){return t*n},symbol:t}}function Fe(t){var e=t.decimal,n=t.thousands,r=t.grouping,i=t.currency,o=r&&n?function(t,e){for(var i=t.length,o=[],a=0,s=r[0],l=0;i>0&&s>0;){l+s+1>e&&(s=Math.max(1,e-l));o.push(t.substring(i-=s,i+s));if((l+=s+1)>e)break;s=r[a=(a+1)%r.length]}return o.reverse().join(n)}:De;return function(t){var n=hl.exec(t),r=n[1]||" ",a=n[2]||">",s=n[3]||"-",l=n[4]||"",u=n[5],c=+n[6],f=n[7],h=n[8],d=n[9],p=1,g="",m="",v=!1,y=!0;h&&(h=+h.substring(1));if(u||"0"===r&&"="===a){u=r="0";a="="}switch(d){case"n":f=!0;d="g";break;case"%":p=100;m="%";d="f";break;case"p":p=100;m="%";d="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+d.toLowerCase());case"c":y=!1;case"d":v=!0;h=0;break;case"s":p=-1;d="r"}"$"===l&&(g=i[0],m=i[1]);"r"!=d||h||(d="g");null!=h&&("g"==d?h=Math.max(1,Math.min(21,h)):("e"==d||"f"==d)&&(h=Math.max(0,Math.min(20,h))));d=dl.get(d)||Re;var b=u&&f;return function(t){var n=m;if(v&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>p){var l=is.formatPrefix(t,h);t=l.scale(t);n=l.symbol+m}else t*=p;t=d(t,h);var x,w,C=t.lastIndexOf(".");if(0>C){var S=y?t.lastIndexOf("e"):-1;0>S?(x=t,w=""):(x=t.substring(0,S),w=t.substring(S))}else{x=t.substring(0,C);w=e+t.substring(C+1)}!u&&f&&(x=o(x,1/0));var T=g.length+x.length+w.length+(b?0:i.length),k=c>T?new Array(T=c-T+1).join(r):"";b&&(x=o(k+x,k.length?c-w.length:1/0));i+=g;t=x+w;return("<"===a?i+t+k:">"===a?k+i+t:"^"===a?k.substring(0,T>>=1)+i+t+k.substring(T):i+(b?t:k+t))+n}}}function Re(t){return t+""}function We(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function ze(t,e,n){function r(e){var n=t(e),r=o(n,1);return r-e>e-n?n:r}function i(n){e(n=t(new gl(n-1)),1);return n}function o(t,n){e(t=new gl(+t),n);return t}function a(t,r,o){var a=i(t),s=[];if(o>1)for(;r>a;){n(a)%o||s.push(new Date(+a));e(a,1)}else for(;r>a;)s.push(new Date(+a)),e(a,1);return s}function s(t,e,n){try{gl=We;var r=new We;r._=t;return a(r,e,n)}finally{gl=Date}}t.floor=t;t.round=r;t.ceil=i;t.offset=o;t.range=a;var l=t.utc=qe(t);l.floor=l;l.round=qe(r);l.ceil=qe(i);l.offset=qe(o);l.range=s;return t}function qe(t){return function(e,n){try{gl=We;var r=new We;r._=e;return t(r,n)._}finally{gl=Date}}}function Ue(t){function e(t){function e(e){for(var n,i,o,a=[],s=-1,l=0;++s<r;)if(37===t.charCodeAt(s)){a.push(t.slice(l,s));null!=(i=vl[n=t.charAt(++s)])&&(n=t.charAt(++s));(o=D[n])&&(n=o(e,null==i?"e"===n?" ":"0":i));a.push(n);l=s+1}a.push(t.slice(l,s));return a.join("")}var r=t.length;e.parse=function(e){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=n(r,t,e,0);if(i!=e.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var o=null!=r.Z&&gl!==We,a=new(o?We:gl);if("j"in r)a.setFullYear(r.y,0,r.j);else if("w"in r&&("W"in r||"U"in r)){a.setFullYear(r.y,0,1);a.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(a.getDay()+5)%7:r.w+7*r.U-(a.getDay()+6)%7)}else a.setFullYear(r.y,r.m,r.d);a.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L);return o?a._:a};e.toString=function(){return t};return e}function n(t,e,n,r){for(var i,o,a,s=0,l=e.length,u=n.length;l>s;){if(r>=u)return-1;i=e.charCodeAt(s++);if(37===i){a=e.charAt(s++);o=L[a in vl?e.charAt(s++):a];if(!o||(r=o(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function r(t,e,n){C.lastIndex=0;var r=C.exec(e.slice(n));return r?(t.w=S.get(r[0].toLowerCase()),n+r[0].length):-1}function i(t,e,n){x.lastIndex=0;var r=x.exec(e.slice(n));return r?(t.w=w.get(r[0].toLowerCase()),n+r[0].length):-1}function o(t,e,n){_.lastIndex=0;var r=_.exec(e.slice(n));return r?(t.m=M.get(r[0].toLowerCase()),n+r[0].length):-1}function a(t,e,n){T.lastIndex=0;var r=T.exec(e.slice(n));return r?(t.m=k.get(r[0].toLowerCase()),n+r[0].length):-1}function s(t,e,r){return n(t,D.c.toString(),e,r)}function l(t,e,r){return n(t,D.x.toString(),e,r)}function u(t,e,r){return n(t,D.X.toString(),e,r)}function c(t,e,n){var r=b.get(e.slice(n,n+=2).toLowerCase());return null==r?-1:(t.p=r,n)}var f=t.dateTime,h=t.date,d=t.time,p=t.periods,g=t.days,m=t.shortDays,v=t.months,y=t.shortMonths;e.utc=function(t){function n(t){try{gl=We;var e=new gl;e._=t;return r(e)}finally{gl=Date}}var r=e(t);n.parse=function(t){try{gl=We;var e=r.parse(t);return e&&e._}finally{gl=Date}};n.toString=r.toString;return n};e.multi=e.utc.multi=cn;var b=is.map(),x=Ve(g),w=Xe(g),C=Ve(m),S=Xe(m),T=Ve(v),k=Xe(v),_=Ve(y),M=Xe(y);p.forEach(function(t,e){b.set(t.toLowerCase(),e)});var D={a:function(t){return m[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return v[t.getMonth()]},c:e(f),d:function(t,e){return Be(t.getDate(),e,2)},e:function(t,e){return Be(t.getDate(),e,2)},H:function(t,e){return Be(t.getHours(),e,2)},I:function(t,e){return Be(t.getHours()%12||12,e,2)},j:function(t,e){return Be(1+pl.dayOfYear(t),e,3)},L:function(t,e){return Be(t.getMilliseconds(),e,3)},m:function(t,e){return Be(t.getMonth()+1,e,2)},M:function(t,e){return Be(t.getMinutes(),e,2)},p:function(t){return p[+(t.getHours()>=12)]},S:function(t,e){return Be(t.getSeconds(),e,2)},U:function(t,e){return Be(pl.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Be(pl.mondayOfYear(t),e,2)},x:e(h),X:e(d),y:function(t,e){return Be(t.getFullYear()%100,e,2)},Y:function(t,e){return Be(t.getFullYear()%1e4,e,4)},Z:ln,"%":function(){return"%"}},L={a:r,A:i,b:o,B:a,c:s,d:en,e:en,H:rn,I:rn,j:nn,L:sn,m:tn,M:on,p:c,S:an,U:$e,w:Ge,W:Ye,x:l,X:u,y:Ke,Y:Je,Z:Ze,"%":un};return e}function Be(t,e,n){var r=0>t?"-":"",i=(r?-t:t)+"",o=i.length;return r+(n>o?new Array(n-o+1).join(e)+i:i)}function Ve(t){return new RegExp("^(?:"+t.map(is.requote).join("|")+")","i")}function Xe(t){for(var e=new u,n=-1,r=t.length;++n<r;)e.set(t[n].toLowerCase(),n);return e}function Ge(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function $e(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n));return r?(t.U=+r[0],n+r[0].length):-1}function Ye(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n));return r?(t.W=+r[0],n+r[0].length):-1}function Je(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Ke(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.y=Qe(+r[0]),n+r[0].length):-1}function Ze(t,e,n){return/^[+-]\d{4}$/.test(e=e.slice(n,n+5))?(t.Z=-e,n+5):-1}function Qe(t){return t+(t>68?1900:2e3)}function tn(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function en(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function nn(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+3));return r?(t.j=+r[0],n+r[0].length):-1}function rn(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function on(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function an(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function sn(t,e,n){yl.lastIndex=0;var r=yl.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function ln(t){var e=t.getTimezoneOffset(),n=e>0?"-":"+",r=ys(e)/60|0,i=ys(e)%60;return n+Be(r,"0",2)+Be(i,"0",2)}function un(t,e,n){bl.lastIndex=0;var r=bl.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function cn(t){for(var e=t.length,n=-1;++n<e;)t[n][0]=this(t[n][0]);return function(e){for(var n=0,r=t[n];!r[1](e);)r=t[++n];return r[0](e)}}function fn(){}function hn(t,e,n){var r=n.s=t+e,i=r-t,o=r-i;n.t=t-o+(e-i)}function dn(t,e){t&&Sl.hasOwnProperty(t.type)&&Sl[t.type](t,e)}function pn(t,e,n){var r,i=-1,o=t.length-n;e.lineStart();for(;++i<o;)r=t[i],e.point(r[0],r[1],r[2]);e.lineEnd()}function gn(t,e){var n=-1,r=t.length;e.polygonStart();for(;++n<r;)pn(t[n],e,1);e.polygonEnd()}function mn(){function t(t,e){t*=qs;e=e*qs/2+Fs/4;var n=t-r,a=n>=0?1:-1,s=a*n,l=Math.cos(e),u=Math.sin(e),c=o*u,f=i*l+c*Math.cos(s),h=c*a*Math.sin(s);kl.add(Math.atan2(h,f));r=t,i=l,o=u}var e,n,r,i,o;_l.point=function(a,s){_l.point=t;r=(e=a)*qs,i=Math.cos(s=(n=s)*qs/2+Fs/4),o=Math.sin(s)};_l.lineEnd=function(){t(e,n)}}function vn(t){var e=t[0],n=t[1],r=Math.cos(n);return[r*Math.cos(e),r*Math.sin(e),Math.sin(n)]}function yn(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function bn(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xn(t,e){t[0]+=e[0];t[1]+=e[1];t[2]+=e[2]}function wn(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Cn(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e;t[1]/=e;t[2]/=e}function Sn(t){return[Math.atan2(t[1],t[0]),ne(t[2])]}function Tn(t,e){return ys(t[0]-e[0])<Hs&&ys(t[1]-e[1])<Hs}function kn(t,e){t*=qs;var n=Math.cos(e*=qs);_n(n*Math.cos(t),n*Math.sin(t),Math.sin(e))}function _n(t,e,n){++Ml;Ll+=(t-Ll)/Ml;Al+=(e-Al)/Ml;Nl+=(n-Nl)/Ml}function Mn(){function t(t,i){t*=qs;var o=Math.cos(i*=qs),a=o*Math.cos(t),s=o*Math.sin(t),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=n*l-r*s)*u+(u=r*a-e*l)*u+(u=e*s-n*a)*u),e*a+n*s+r*l);Dl+=u;El+=u*(e+(e=a));jl+=u*(n+(n=s));Il+=u*(r+(r=l));_n(e,n,r)}var e,n,r;Fl.point=function(i,o){i*=qs;var a=Math.cos(o*=qs);e=a*Math.cos(i);n=a*Math.sin(i);r=Math.sin(o);Fl.point=t;_n(e,n,r)}}function Dn(){Fl.point=kn}function Ln(){function t(t,e){t*=qs;var n=Math.cos(e*=qs),a=n*Math.cos(t),s=n*Math.sin(t),l=Math.sin(e),u=i*l-o*s,c=o*a-r*l,f=r*s-i*a,h=Math.sqrt(u*u+c*c+f*f),d=r*a+i*s+o*l,p=h&&-ee(d)/h,g=Math.atan2(h,d);Pl+=p*u;Hl+=p*c;Ol+=p*f;Dl+=g;El+=g*(r+(r=a));jl+=g*(i+(i=s));Il+=g*(o+(o=l));_n(r,i,o)}var e,n,r,i,o;Fl.point=function(a,s){e=a,n=s;Fl.point=t;a*=qs;var l=Math.cos(s*=qs);r=l*Math.cos(a);i=l*Math.sin(a);o=Math.sin(s);_n(r,i,o)};Fl.lineEnd=function(){t(e,n);Fl.lineEnd=Dn;Fl.point=kn}}function An(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}t.invert&&e.invert&&(n.invert=function(n,r){return n=e.invert(n,r),n&&t.invert(n[0],n[1])});return n}function Nn(){return!0}function En(t,e,n,r,i){var o=[],a=[];t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,n=t[0],r=t[e];if(Tn(n,r)){i.lineStart();for(var s=0;e>s;++s)i.point((n=t[s])[0],n[1]);i.lineEnd()}else{var l=new In(n,t,null,!0),u=new In(n,null,l,!1);l.o=u;o.push(l);a.push(u);l=new In(r,t,null,!1);u=new In(r,null,l,!0);l.o=u;o.push(l);a.push(u)}}});a.sort(e);jn(o);jn(a);if(o.length){for(var s=0,l=n,u=a.length;u>s;++s)a[s].e=l=!l;for(var c,f,h=o[0];;){for(var d=h,p=!0;d.v;)if((d=d.n)===h)return;c=d.z;i.lineStart();do{d.v=d.o.v=!0;if(d.e){if(p)for(var s=0,u=c.length;u>s;++s)i.point((f=c[s])[0],f[1]);else r(d.x,d.n.x,1,i);d=d.n}else{if(p){c=d.p.z;for(var s=c.length-1;s>=0;--s)i.point((f=c[s])[0],f[1])}else r(d.x,d.p.x,-1,i);d=d.p}d=d.o;c=d.z;p=!p}while(!d.v);i.lineEnd()}}}function jn(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r<e;){i.n=n=t[r];n.p=i;i=n}i.n=n=t[0];n.p=i}}function In(t,e,n,r){this.x=t;this.z=e;this.o=n;this.e=r;this.v=!1;this.n=this.p=null}function Pn(t,e,n,r){return function(i,o){function a(e,n){var r=i(e,n);t(e=r[0],n=r[1])&&o.point(e,n)}function s(t,e){var n=i(t,e);m.point(n[0],n[1])}function l(){y.point=s;m.lineStart()}function u(){y.point=a;m.lineEnd()}function c(t,e){g.push([t,e]);var n=i(t,e);x.point(n[0],n[1])}function f(){x.lineStart();g=[]}function h(){c(g[0][0],g[0][1]);x.lineEnd();var t,e=x.clean(),n=b.buffer(),r=n.length;g.pop();p.push(g);g=null;if(r)if(1&e){t=n[0];var i,r=t.length-1,a=-1;if(r>0){w||(o.polygonStart(),w=!0);o.lineStart();for(;++a<r;)o.point((i=t[a])[0],i[1]);o.lineEnd()}}else{r>1&&2&e&&n.push(n.pop().concat(n.shift()));d.push(n.filter(Hn))}}var d,p,g,m=e(o),v=i.invert(r[0],r[1]),y={point:a,lineStart:l,lineEnd:u,polygonStart:function(){y.point=c;y.lineStart=f;y.lineEnd=h;d=[];p=[]},polygonEnd:function(){y.point=a;y.lineStart=l;y.lineEnd=u;d=is.merge(d);var t=qn(v,p);if(d.length){w||(o.polygonStart(),w=!0);En(d,Fn,t,n,o)}else if(t){w||(o.polygonStart(),w=!0);o.lineStart();n(null,null,1,o);o.lineEnd()}w&&(o.polygonEnd(),w=!1);d=p=null},sphere:function(){o.polygonStart();o.lineStart();n(null,null,1,o);o.lineEnd();o.polygonEnd()}},b=On(),x=e(b),w=!1;return y}}function Hn(t){return t.length>1}function On(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,n){t.push([e,n])},lineEnd:x,buffer:function(){var n=e;e=[];t=null;return n},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fn(t,e){return((t=t.x)[0]<0?t[1]-zs-Hs:zs-t[1])-((e=e.x)[0]<0?e[1]-zs-Hs:zs-e[1])}function Rn(t){var e,n=0/0,r=0/0,i=0/0;return{lineStart:function(){t.lineStart();e=1},point:function(o,a){var s=o>0?Fs:-Fs,l=ys(o-n);if(ys(l-Fs)<Hs){t.point(n,r=(r+a)/2>0?zs:-zs);t.point(i,r);t.lineEnd();t.lineStart();t.point(s,r);t.point(o,r);e=0}else if(i!==s&&l>=Fs){ys(n-i)<Hs&&(n-=i*Hs);ys(o-s)<Hs&&(o-=s*Hs);r=Wn(n,r,o,a);t.point(i,r);t.lineEnd();t.lineStart();t.point(s,r);e=0}t.point(n=o,r=a);i=s},lineEnd:function(){t.lineEnd();n=r=0/0},clean:function(){return 2-e}}}function Wn(t,e,n,r){var i,o,a=Math.sin(t-n);return ys(a)>Hs?Math.atan((Math.sin(e)*(o=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(e))*Math.sin(t))/(i*o*a)):(e+r)/2}function zn(t,e,n,r){var i;if(null==t){i=n*zs;r.point(-Fs,i);r.point(0,i);r.point(Fs,i);r.point(Fs,0);r.point(Fs,-i);r.point(0,-i);r.point(-Fs,-i);r.point(-Fs,0);r.point(-Fs,i)}else if(ys(t[0]-e[0])>Hs){var o=t[0]<e[0]?Fs:-Fs;i=n*o/2;r.point(-o,i);r.point(0,i);r.point(o,i)}else r.point(e[0],e[1])}function qn(t,e){var n=t[0],r=t[1],i=[Math.sin(n),-Math.cos(n),0],o=0,a=0;kl.reset();for(var s=0,l=e.length;l>s;++s){var u=e[s],c=u.length;if(c)for(var f=u[0],h=f[0],d=f[1]/2+Fs/4,p=Math.sin(d),g=Math.cos(d),m=1;;){m===c&&(m=0);t=u[m];var v=t[0],y=t[1]/2+Fs/4,b=Math.sin(y),x=Math.cos(y),w=v-h,C=w>=0?1:-1,S=C*w,T=S>Fs,k=p*b;kl.add(Math.atan2(k*C*Math.sin(S),g*x+k*Math.cos(S)));o+=T?w+C*Rs:w;if(T^h>=n^v>=n){var _=bn(vn(f),vn(t));Cn(_);var M=bn(i,_);Cn(M);var D=(T^w>=0?-1:1)*ne(M[2]);(r>D||r===D&&(_[0]||_[1]))&&(a+=T^w>=0?1:-1)}if(!m++)break;h=v,p=b,g=x,f=t}}return(-Hs>o||Hs>o&&0>kl)^1&a}function Un(t){function e(t,e){return Math.cos(t)*Math.cos(e)>o}function n(t){var n,o,l,u,c;return{lineStart:function(){u=l=!1;c=1},point:function(f,h){var d,p=[f,h],g=e(f,h),m=a?g?0:i(f,h):g?i(f+(0>f?Fs:-Fs),h):0;!n&&(u=l=g)&&t.lineStart();if(g!==l){d=r(n,p);if(Tn(n,d)||Tn(p,d)){p[0]+=Hs;p[1]+=Hs;g=e(p[0],p[1])}}if(g!==l){c=0;if(g){t.lineStart();d=r(p,n);t.point(d[0],d[1])}else{d=r(n,p);t.point(d[0],d[1]);t.lineEnd()}n=d}else if(s&&n&&a^g){var v;if(!(m&o)&&(v=r(p,n,!0))){c=0;if(a){t.lineStart();t.point(v[0][0],v[0][1]);t.point(v[1][0],v[1][1]);t.lineEnd()}else{t.point(v[1][0],v[1][1]);t.lineEnd();t.lineStart();t.point(v[0][0],v[0][1])}}}!g||n&&Tn(n,p)||t.point(p[0],p[1]);n=p,l=g,o=m},lineEnd:function(){l&&t.lineEnd();n=null},clean:function(){return c|(u&&l)<<1}}}function r(t,e,n){var r=vn(t),i=vn(e),a=[1,0,0],s=bn(r,i),l=yn(s,s),u=s[0],c=l-u*u;if(!c)return!n&&t;var f=o*l/c,h=-o*u/c,d=bn(a,s),p=wn(a,f),g=wn(s,h);xn(p,g);var m=d,v=yn(p,m),y=yn(m,m),b=v*v-y*(yn(p,p)-1);if(!(0>b)){var x=Math.sqrt(b),w=wn(m,(-v-x)/y);xn(w,p);w=Sn(w);if(!n)return w;var C,S=t[0],T=e[0],k=t[1],_=e[1];S>T&&(C=S,S=T,T=C);var M=T-S,D=ys(M-Fs)<Hs,L=D||Hs>M;!D&&k>_&&(C=k,k=_,_=C);if(L?D?k+_>0^w[1]<(ys(w[0]-S)<Hs?k:_):k<=w[1]&&w[1]<=_:M>Fs^(S<=w[0]&&w[0]<=T)){var A=wn(m,(-v+x)/y);xn(A,p);return[w,Sn(A)]}}}function i(e,n){var r=a?t:Fs-t,i=0;-r>e?i|=1:e>r&&(i|=2);-r>n?i|=4:n>r&&(i|=8);return i}var o=Math.cos(t),a=o>0,s=ys(o)>Hs,l=mr(t,6*qs);return Pn(e,n,l,a?[0,-t]:[-Fs,t-Fs])}function Bn(t,e,n,r){return function(i){var o,a=i.a,s=i.b,l=a.x,u=a.y,c=s.x,f=s.y,h=0,d=1,p=c-l,g=f-u;o=t-l;if(p||!(o>0)){o/=p;if(0>p){if(h>o)return;d>o&&(d=o)}else if(p>0){if(o>d)return;o>h&&(h=o)}o=n-l;if(p||!(0>o)){o/=p;if(0>p){if(o>d)return;o>h&&(h=o)}else if(p>0){if(h>o)return;d>o&&(d=o)}o=e-u;if(g||!(o>0)){o/=g;if(0>g){if(h>o)return;d>o&&(d=o)}else if(g>0){if(o>d)return;o>h&&(h=o)}o=r-u;if(g||!(0>o)){o/=g;if(0>g){if(o>d)return;o>h&&(h=o)}else if(g>0){if(h>o)return;d>o&&(d=o)}h>0&&(i.a={x:l+h*p,y:u+h*g});1>d&&(i.b={x:l+d*p,y:u+d*g});return i}}}}}}function Vn(t,e,n,r){function i(r,i){return ys(r[0]-t)<Hs?i>0?0:3:ys(r[0]-n)<Hs?i>0?2:1:ys(r[1]-e)<Hs?i>0?1:0:i>0?3:2}function o(t,e){return a(t.x,e.x)}function a(t,e){var n=i(t,1),r=i(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,n=m.length,r=t[1],i=0;n>i;++i)for(var o,a=1,s=m[i],l=s.length,u=s[0];l>a;++a){o=s[a];u[1]<=r?o[1]>r&&te(u,o,t)>0&&++e:o[1]<=r&&te(u,o,t)<0&&--e;u=o}return 0!==e}function u(o,s,l,u){var c=0,f=0;if(null==o||(c=i(o,l))!==(f=i(s,l))||a(o,s)<0^l>0){do u.point(0===c||3===c?t:n,c>1?r:e);while((c=(c+l+4)%4)!==f)}else u.point(s[0],s[1])}function c(i,o){return i>=t&&n>=i&&o>=e&&r>=o}function f(t,e){c(t,e)&&s.point(t,e)}function h(){L.point=p;m&&m.push(v=[]);T=!0;S=!1;w=C=0/0}function d(){if(g){p(y,b);x&&S&&M.rejoin();g.push(M.buffer())}L.point=f;S&&s.lineEnd()}function p(t,e){t=Math.max(-Wl,Math.min(Wl,t));e=Math.max(-Wl,Math.min(Wl,e));var n=c(t,e);m&&v.push([t,e]);if(T){y=t,b=e,x=n;T=!1;if(n){s.lineStart();s.point(t,e)}}else if(n&&S)s.point(t,e);else{var r={a:{x:w,y:C},b:{x:t,y:e}};if(D(r)){if(!S){s.lineStart();s.point(r.a.x,r.a.y)}s.point(r.b.x,r.b.y);n||s.lineEnd();k=!1}else if(n){s.lineStart();s.point(t,e);k=!1}}w=t,C=e,S=n}var g,m,v,y,b,x,w,C,S,T,k,_=s,M=On(),D=Bn(t,e,n,r),L={point:f,lineStart:h,lineEnd:d,polygonStart:function(){s=M;g=[];m=[];k=!0},polygonEnd:function(){s=_;g=is.merge(g);var e=l([t,r]),n=k&&e,i=g.length;if(n||i){s.polygonStart();if(n){s.lineStart();u(null,null,1,s);s.lineEnd()}i&&En(g,o,e,u,s);s.polygonEnd()}g=m=v=null}};return L}}function Xn(t){var e=0,n=Fs/3,r=lr(t),i=r(e,n);i.parallels=function(t){return arguments.length?r(e=t[0]*Fs/180,n=t[1]*Fs/180):[e/Fs*180,n/Fs*180]};return i}function Gn(t,e){function n(t,e){var n=Math.sqrt(o-2*i*Math.sin(e))/i;return[n*Math.sin(t*=i),a-n*Math.cos(t)]}var r=Math.sin(t),i=(r+Math.sin(e))/2,o=1+r*(2*i-r),a=Math.sqrt(o)/i;n.invert=function(t,e){var n=a-e;return[Math.atan2(t,n)/i,ne((o-(t*t+n*n)*i*i)/(2*i))]};return n}function $n(){function t(t,e){ql+=i*t-r*e;r=t,i=e}var e,n,r,i;Gl.point=function(o,a){Gl.point=t;e=r=o,n=i=a};Gl.lineEnd=function(){t(e,n)}}function Yn(t,e){Ul>t&&(Ul=t);t>Vl&&(Vl=t);Bl>e&&(Bl=e);e>Xl&&(Xl=e)}function Jn(){function t(t,e){a.push("M",t,",",e,o)}function e(t,e){a.push("M",t,",",e);s.point=n}function n(t,e){a.push("L",t,",",e)}function r(){s.point=t}function i(){a.push("Z")}var o=Kn(4.5),a=[],s={point:t,lineStart:function(){s.point=e},lineEnd:r,polygonStart:function(){s.lineEnd=i},polygonEnd:function(){s.lineEnd=r;s.point=t},pointRadius:function(t){o=Kn(t);return s},result:function(){if(a.length){var t=a.join("");a=[];return t}}};return s}function Kn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Zn(t,e){Ll+=t;Al+=e;++Nl}function Qn(){function t(t,r){var i=t-e,o=r-n,a=Math.sqrt(i*i+o*o);El+=a*(e+t)/2;jl+=a*(n+r)/2;Il+=a;Zn(e=t,n=r)}var e,n;Yl.point=function(r,i){Yl.point=t;Zn(e=r,n=i)}}function tr(){Yl.point=Zn}function er(){function t(t,e){var n=t-r,o=e-i,a=Math.sqrt(n*n+o*o);El+=a*(r+t)/2;jl+=a*(i+e)/2;Il+=a;a=i*t-r*e;Pl+=a*(r+t);Hl+=a*(i+e);Ol+=3*a;Zn(r=t,i=e)}var e,n,r,i;Yl.point=function(o,a){Yl.point=t;Zn(e=r=o,n=i=a)};Yl.lineEnd=function(){t(e,n)}}function nr(t){function e(e,n){t.moveTo(e+a,n);t.arc(e,n,a,0,Rs)}function n(e,n){t.moveTo(e,n);s.point=r}function r(e,n){t.lineTo(e,n)}function i(){s.point=e}function o(){t.closePath()}var a=4.5,s={point:e,lineStart:function(){s.point=n},lineEnd:i,polygonStart:function(){s.lineEnd=o},polygonEnd:function(){s.lineEnd=i;s.point=e},pointRadius:function(t){a=t;return s},result:x};return s}function rr(t){function e(t){return(s?r:n)(t)}function n(e){return ar(e,function(n,r){n=t(n,r);e.point(n[0],n[1])})}function r(e){function n(n,r){n=t(n,r);e.point(n[0],n[1])}function r(){b=0/0;T.point=o;e.lineStart()}function o(n,r){var o=vn([n,r]),a=t(n,r);i(b,x,y,w,C,S,b=a[0],x=a[1],y=n,w=o[0],C=o[1],S=o[2],s,e);e.point(b,x)}function a(){T.point=n;e.lineEnd()}function l(){r();T.point=u;T.lineEnd=c}function u(t,e){o(f=t,h=e),d=b,p=x,g=w,m=C,v=S;T.point=o}function c(){i(b,x,y,w,C,S,d,p,f,g,m,v,s,e); T.lineEnd=a;a()}var f,h,d,p,g,m,v,y,b,x,w,C,S,T={point:n,lineStart:r,lineEnd:a,polygonStart:function(){e.polygonStart();T.lineStart=l},polygonEnd:function(){e.polygonEnd();T.lineStart=r}};return T}function i(e,n,r,s,l,u,c,f,h,d,p,g,m,v){var y=c-e,b=f-n,x=y*y+b*b;if(x>4*o&&m--){var w=s+d,C=l+p,S=u+g,T=Math.sqrt(w*w+C*C+S*S),k=Math.asin(S/=T),_=ys(ys(S)-1)<Hs||ys(r-h)<Hs?(r+h)/2:Math.atan2(C,w),M=t(_,k),D=M[0],L=M[1],A=D-e,N=L-n,E=b*A-y*N;if(E*E/x>o||ys((y*A+b*N)/x-.5)>.3||a>s*d+l*p+u*g){i(e,n,r,s,l,u,D,L,_,w/=T,C/=T,S,m,v);v.point(D,L);i(D,L,_,w,C,S,c,f,h,d,p,g,m,v)}}}var o=.5,a=Math.cos(30*qs),s=16;e.precision=function(t){if(!arguments.length)return Math.sqrt(o);s=(o=t*t)>0&&16;return e};return e}function ir(t){var e=rr(function(e,n){return t([e*Us,n*Us])});return function(t){return ur(e(t))}}function or(t){this.stream=t}function ar(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){t=s(t[0]*qs,t[1]*qs);return[t[0]*h+l,u-t[1]*h]}function n(t){t=s.invert((t[0]-l)/h,(u-t[1])/h);return t&&[t[0]*Us,t[1]*Us]}function r(){s=An(a=hr(v,y,b),o);var t=o(g,m);l=d-t[0]*h;u=p+t[1]*h;return i()}function i(){c&&(c.valid=!1,c=null);return e}var o,a,s,l,u,c,f=rr(function(t,e){t=o(t,e);return[t[0]*h+l,u-t[1]*h]}),h=150,d=480,p=250,g=0,m=0,v=0,y=0,b=0,x=Rl,w=De,C=null,S=null;e.stream=function(t){c&&(c.valid=!1);c=ur(x(a,f(w(t))));c.valid=!0;return c};e.clipAngle=function(t){if(!arguments.length)return C;x=null==t?(C=t,Rl):Un((C=+t)*qs);return i()};e.clipExtent=function(t){if(!arguments.length)return S;S=t;w=t?Vn(t[0][0],t[0][1],t[1][0],t[1][1]):De;return i()};e.scale=function(t){if(!arguments.length)return h;h=+t;return r()};e.translate=function(t){if(!arguments.length)return[d,p];d=+t[0];p=+t[1];return r()};e.center=function(t){if(!arguments.length)return[g*Us,m*Us];g=t[0]%360*qs;m=t[1]%360*qs;return r()};e.rotate=function(t){if(!arguments.length)return[v*Us,y*Us,b*Us];v=t[0]%360*qs;y=t[1]%360*qs;b=t.length>2?t[2]%360*qs:0;return r()};is.rebind(e,f,"precision");return function(){o=t.apply(this,arguments);e.invert=o.invert&&n;return r()}}function ur(t){return ar(t,function(e,n){t.point(e*qs,n*qs)})}function cr(t,e){return[t,e]}function fr(t,e){return[t>Fs?t-Rs:-Fs>t?t+Rs:t,e]}function hr(t,e,n){return t?e||n?An(pr(t),gr(e,n)):pr(t):e||n?gr(e,n):fr}function dr(t){return function(e,n){return e+=t,[e>Fs?e-Rs:-Fs>e?e+Rs:e,n]}}function pr(t){var e=dr(t);e.invert=dr(-t);return e}function gr(t,e){function n(t,e){var n=Math.cos(e),s=Math.cos(t)*n,l=Math.sin(t)*n,u=Math.sin(e),c=u*r+s*i;return[Math.atan2(l*o-c*a,s*r-u*i),ne(c*o+l*a)]}var r=Math.cos(t),i=Math.sin(t),o=Math.cos(e),a=Math.sin(e);n.invert=function(t,e){var n=Math.cos(e),s=Math.cos(t)*n,l=Math.sin(t)*n,u=Math.sin(e),c=u*o-l*a;return[Math.atan2(l*o+u*a,s*r+c*i),ne(c*r-s*i)]};return n}function mr(t,e){var n=Math.cos(t),r=Math.sin(t);return function(i,o,a,s){var l=a*e;if(null!=i){i=vr(n,i);o=vr(n,o);(a>0?o>i:i>o)&&(i+=a*Rs)}else{i=t+a*Rs;o=t-.5*l}for(var u,c=i;a>0?c>o:o>c;c-=l)s.point((u=Sn([n,-r*Math.cos(c),-r*Math.sin(c)]))[0],u[1])}}function vr(t,e){var n=vn(e);n[0]-=t;Cn(n);var r=ee(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-Hs)%(2*Math.PI)}function yr(t,e,n){var r=is.range(t,e-Hs,n).concat(e);return function(t){return r.map(function(e){return[t,e]})}}function br(t,e,n){var r=is.range(t,e-Hs,n).concat(e);return function(t){return r.map(function(e){return[e,t]})}}function xr(t){return t.source}function wr(t){return t.target}function Cr(t,e,n,r){var i=Math.cos(e),o=Math.sin(e),a=Math.cos(r),s=Math.sin(r),l=i*Math.cos(t),u=i*Math.sin(t),c=a*Math.cos(n),f=a*Math.sin(n),h=2*Math.asin(Math.sqrt(ae(r-e)+i*a*ae(n-t))),d=1/Math.sin(h),p=h?function(t){var e=Math.sin(t*=h)*d,n=Math.sin(h-t)*d,r=n*l+e*c,i=n*u+e*f,a=n*o+e*s;return[Math.atan2(i,r)*Us,Math.atan2(a,Math.sqrt(r*r+i*i))*Us]}:function(){return[t*Us,e*Us]};p.distance=h;return p}function Sr(){function t(t,i){var o=Math.sin(i*=qs),a=Math.cos(i),s=ys((t*=qs)-e),l=Math.cos(s);Jl+=Math.atan2(Math.sqrt((s=a*Math.sin(s))*s+(s=r*o-n*a*l)*s),n*o+r*a*l);e=t,n=o,r=a}var e,n,r;Kl.point=function(i,o){e=i*qs,n=Math.sin(o*=qs),r=Math.cos(o);Kl.point=t};Kl.lineEnd=function(){Kl.point=Kl.lineEnd=x}}function Tr(t,e){function n(e,n){var r=Math.cos(e),i=Math.cos(n),o=t(r*i);return[o*i*Math.sin(e),o*Math.sin(n)]}n.invert=function(t,n){var r=Math.sqrt(t*t+n*n),i=e(r),o=Math.sin(i),a=Math.cos(i);return[Math.atan2(t*o,r*a),Math.asin(r&&n*o/r)]};return n}function kr(t,e){function n(t,e){a>0?-zs+Hs>e&&(e=-zs+Hs):e>zs-Hs&&(e=zs-Hs);var n=a/Math.pow(i(e),o);return[n*Math.sin(o*t),a-n*Math.cos(o*t)]}var r=Math.cos(t),i=function(t){return Math.tan(Fs/4+t/2)},o=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(i(e)/i(t)),a=r*Math.pow(i(t),o)/o;if(!o)return Mr;n.invert=function(t,e){var n=a-e,r=Q(o)*Math.sqrt(t*t+n*n);return[Math.atan2(t,n)/o,2*Math.atan(Math.pow(a/r,1/o))-zs]};return n}function _r(t,e){function n(t,e){var n=o-e;return[n*Math.sin(i*t),o-n*Math.cos(i*t)]}var r=Math.cos(t),i=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),o=r/i+t;if(ys(i)<Hs)return cr;n.invert=function(t,e){var n=o-e;return[Math.atan2(t,n)/i,o-Q(i)*Math.sqrt(t*t+n*n)]};return n}function Mr(t,e){return[t,Math.log(Math.tan(Fs/4+e/2))]}function Dr(t){var e,n=sr(t),r=n.scale,i=n.translate,o=n.clipExtent;n.scale=function(){var t=r.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t};n.translate=function(){var t=i.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t};n.clipExtent=function(t){var a=o.apply(n,arguments);if(a===n){if(e=null==t){var s=Fs*r(),l=i();o([[l[0]-s,l[1]-s],[l[0]+s,l[1]+s]])}}else e&&(a=null);return a};return n.clipExtent(null)}function Lr(t,e){return[Math.log(Math.tan(Fs/4+e/2)),-t]}function Ar(t){return t[0]}function Nr(t){return t[1]}function Er(t){for(var e=t.length,n=[0,1],r=2,i=2;e>i;i++){for(;r>1&&te(t[n[r-2]],t[n[r-1]],t[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function jr(t,e){return t[0]-e[0]||t[1]-e[1]}function Ir(t,e,n){return(n[0]-e[0])*(t[1]-e[1])<(n[1]-e[1])*(t[0]-e[0])}function Pr(t,e,n,r){var i=t[0],o=n[0],a=e[0]-i,s=r[0]-o,l=t[1],u=n[1],c=e[1]-l,f=r[1]-u,h=(s*(l-u)-f*(i-o))/(f*a-s*c);return[i+h*a,l+h*c]}function Hr(t){var e=t[0],n=t[t.length-1];return!(e[0]-n[0]||e[1]-n[1])}function Or(){ii(this);this.edge=this.site=this.circle=null}function Fr(t){var e=uu.pop()||new Or;e.site=t;return e}function Rr(t){Yr(t);au.remove(t);uu.push(t);ii(t)}function Wr(t){var e=t.circle,n=e.x,r=e.cy,i={x:n,y:r},o=t.P,a=t.N,s=[t];Rr(t);for(var l=o;l.circle&&ys(n-l.circle.x)<Hs&&ys(r-l.circle.cy)<Hs;){o=l.P;s.unshift(l);Rr(l);l=o}s.unshift(l);Yr(l);for(var u=a;u.circle&&ys(n-u.circle.x)<Hs&&ys(r-u.circle.cy)<Hs;){a=u.N;s.push(u);Rr(u);u=a}s.push(u);Yr(u);var c,f=s.length;for(c=1;f>c;++c){u=s[c];l=s[c-1];ei(u.edge,l.site,u.site,i)}l=s[0];u=s[f-1];u.edge=Qr(l.site,u.site,null,i);$r(l);$r(u)}function zr(t){for(var e,n,r,i,o=t.x,a=t.y,s=au._;s;){r=qr(s,a)-o;if(r>Hs)s=s.L;else{i=o-Ur(s,a);if(!(i>Hs)){if(r>-Hs){e=s.P;n=s}else if(i>-Hs){e=s;n=s.N}else e=n=s;break}if(!s.R){e=s;break}s=s.R}}var l=Fr(t);au.insert(e,l);if(e||n)if(e!==n)if(n){Yr(e);Yr(n);var u=e.site,c=u.x,f=u.y,h=t.x-c,d=t.y-f,p=n.site,g=p.x-c,m=p.y-f,v=2*(h*m-d*g),y=h*h+d*d,b=g*g+m*m,x={x:(m*y-d*b)/v+c,y:(h*b-g*y)/v+f};ei(n.edge,u,p,x);l.edge=Qr(u,t,null,x);n.edge=Qr(t,p,null,x);$r(e);$r(n)}else l.edge=Qr(e.site,l.site);else{Yr(e);n=Fr(e.site);au.insert(l,n);l.edge=n.edge=Qr(e.site,l.site);$r(e);$r(n)}}function qr(t,e){var n=t.site,r=n.x,i=n.y,o=i-e;if(!o)return r;var a=t.P;if(!a)return-1/0;n=a.site;var s=n.x,l=n.y,u=l-e;if(!u)return s;var c=s-r,f=1/o-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-l+u/2+i-o/2)))/f+r:(r+s)/2}function Ur(t,e){var n=t.N;if(n)return qr(n,e);var r=t.site;return r.y===e?r.x:1/0}function Br(t){this.site=t;this.edges=[]}function Vr(t){for(var e,n,r,i,o,a,s,l,u,c,f=t[0][0],h=t[1][0],d=t[0][1],p=t[1][1],g=ou,m=g.length;m--;){o=g[m];if(o&&o.prepare()){s=o.edges;l=s.length;a=0;for(;l>a;){c=s[a].end(),r=c.x,i=c.y;u=s[++a%l].start(),e=u.x,n=u.y;if(ys(r-e)>Hs||ys(i-n)>Hs){s.splice(a,0,new ni(ti(o.site,c,ys(r-f)<Hs&&p-i>Hs?{x:f,y:ys(e-f)<Hs?n:p}:ys(i-p)<Hs&&h-r>Hs?{x:ys(n-p)<Hs?e:h,y:p}:ys(r-h)<Hs&&i-d>Hs?{x:h,y:ys(e-h)<Hs?n:d}:ys(i-d)<Hs&&r-f>Hs?{x:ys(n-d)<Hs?e:f,y:d}:null),o.site,null));++l}}}}}function Xr(t,e){return e.angle-t.angle}function Gr(){ii(this);this.x=this.y=this.arc=this.site=this.cy=null}function $r(t){var e=t.P,n=t.N;if(e&&n){var r=e.site,i=t.site,o=n.site;if(r!==o){var a=i.x,s=i.y,l=r.x-a,u=r.y-s,c=o.x-a,f=o.y-s,h=2*(l*f-u*c);if(!(h>=-Os)){var d=l*l+u*u,p=c*c+f*f,g=(f*d-u*p)/h,m=(l*p-c*d)/h,f=m+s,v=cu.pop()||new Gr;v.arc=t;v.site=i;v.x=g+a;v.y=f+Math.sqrt(g*g+m*m);v.cy=f;t.circle=v;for(var y=null,b=lu._;b;)if(v.y<b.y||v.y===b.y&&v.x<=b.x){if(!b.L){y=b.P;break}b=b.L}else{if(!b.R){y=b;break}b=b.R}lu.insert(y,v);y||(su=v)}}}}function Yr(t){var e=t.circle;if(e){e.P||(su=e.N);lu.remove(e);cu.push(e);ii(e);t.circle=null}}function Jr(t){for(var e,n=iu,r=Bn(t[0][0],t[0][1],t[1][0],t[1][1]),i=n.length;i--;){e=n[i];if(!Kr(e,t)||!r(e)||ys(e.a.x-e.b.x)<Hs&&ys(e.a.y-e.b.y)<Hs){e.a=e.b=null;n.splice(i,1)}}}function Kr(t,e){var n=t.b;if(n)return!0;var r,i,o=t.a,a=e[0][0],s=e[1][0],l=e[0][1],u=e[1][1],c=t.l,f=t.r,h=c.x,d=c.y,p=f.x,g=f.y,m=(h+p)/2,v=(d+g)/2;if(g===d){if(a>m||m>=s)return;if(h>p){if(o){if(o.y>=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y<l)return}else o={x:m,y:u};n={x:m,y:l}}}else{r=(h-p)/(g-d);i=v-r*m;if(-1>r||r>1)if(h>p){if(o){if(o.y>=u)return}else o={x:(l-i)/r,y:l};n={x:(u-i)/r,y:u}}else{if(o){if(o.y<l)return}else o={x:(u-i)/r,y:u};n={x:(l-i)/r,y:l}}else if(g>d){if(o){if(o.x>=s)return}else o={x:a,y:r*a+i};n={x:s,y:r*s+i}}else{if(o){if(o.x<a)return}else o={x:s,y:r*s+i};n={x:a,y:r*a+i}}}t.a=o;t.b=n;return!0}function Zr(t,e){this.l=t;this.r=e;this.a=this.b=null}function Qr(t,e,n,r){var i=new Zr(t,e);iu.push(i);n&&ei(i,t,e,n);r&&ei(i,e,t,r);ou[t.i].edges.push(new ni(i,t,e));ou[e.i].edges.push(new ni(i,e,t));return i}function ti(t,e,n){var r=new Zr(t,null);r.a=e;r.b=n;iu.push(r);return r}function ei(t,e,n,r){if(t.a||t.b)t.l===n?t.b=r:t.a=r;else{t.a=r;t.l=e;t.r=n}}function ni(t,e,n){var r=t.a,i=t.b;this.edge=t;this.site=e;this.angle=n?Math.atan2(n.y-e.y,n.x-e.x):t.l===e?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function ri(){this._=null}function ii(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function oi(t,e){var n=e,r=e.R,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r;r.U=i;n.U=r;n.R=r.L;n.R&&(n.R.U=n);r.L=n}function ai(t,e){var n=e,r=e.L,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r;r.U=i;n.U=r;n.L=r.R;n.L&&(n.L.U=n);r.R=n}function si(t){for(;t.L;)t=t.L;return t}function li(t,e){var n,r,i,o=t.sort(ui).pop();iu=[];ou=new Array(t.length);au=new ri;lu=new ri;for(;;){i=su;if(o&&(!i||o.y<i.y||o.y===i.y&&o.x<i.x)){if(o.x!==n||o.y!==r){ou[o.i]=new Br(o);zr(o);n=o.x,r=o.y}o=t.pop()}else{if(!i)break;Wr(i.arc)}}e&&(Jr(e),Vr(e));var a={cells:ou,edges:iu};au=lu=iu=ou=null;return a}function ui(t,e){return e.y-t.y||e.x-t.x}function ci(t,e,n){return(t.x-n.x)*(e.y-t.y)-(t.x-e.x)*(n.y-t.y)}function fi(t){return t.x}function hi(t){return t.y}function di(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function pi(t,e,n,r,i,o){if(!t(e,n,r,i,o)){var a=.5*(n+i),s=.5*(r+o),l=e.nodes;l[0]&&pi(t,l[0],n,r,a,s);l[1]&&pi(t,l[1],a,r,i,s);l[2]&&pi(t,l[2],n,s,a,o);l[3]&&pi(t,l[3],a,s,i,o)}}function gi(t,e,n,r,i,o,a){var s,l=1/0;(function u(t,c,f,h,d){if(!(c>o||f>a||r>h||i>d)){if(p=t.point){var p,g=e-p[0],m=n-p[1],v=g*g+m*m;if(l>v){var y=Math.sqrt(l=v);r=e-y,i=n-y;o=e+y,a=n+y;s=p}}for(var b=t.nodes,x=.5*(c+h),w=.5*(f+d),C=e>=x,S=n>=w,T=S<<1|C,k=T+4;k>T;++T)if(t=b[3&T])switch(3&T){case 0:u(t,c,f,x,w);break;case 1:u(t,x,f,h,w);break;case 2:u(t,c,w,x,d);break;case 3:u(t,x,w,h,d)}}})(t,r,i,o,a);return s}function mi(t,e){t=is.rgb(t);e=is.rgb(e);var n=t.r,r=t.g,i=t.b,o=e.r-n,a=e.g-r,s=e.b-i;return function(t){return"#"+we(Math.round(n+o*t))+we(Math.round(r+a*t))+we(Math.round(i+s*t))}}function vi(t,e){var n,r={},i={};for(n in t)n in e?r[n]=xi(t[n],e[n]):i[n]=t[n];for(n in e)n in t||(i[n]=e[n]);return function(t){for(n in r)i[n]=r[n](t);return i}}function yi(t,e){t=+t,e=+e;return function(n){return t*(1-n)+e*n}}function bi(t,e){var n,r,i,o=hu.lastIndex=du.lastIndex=0,a=-1,s=[],l=[];t+="",e+="";for(;(n=hu.exec(t))&&(r=du.exec(e));){if((i=r.index)>o){i=e.slice(o,i);s[a]?s[a]+=i:s[++a]=i}if((n=n[0])===(r=r[0]))s[a]?s[a]+=r:s[++a]=r;else{s[++a]=null;l.push({i:a,x:yi(n,r)})}o=du.lastIndex}if(o<e.length){i=e.slice(o);s[a]?s[a]+=i:s[++a]=i}return s.length<2?l[0]?(e=l[0].x,function(t){return e(t)+""}):function(){return e}:(e=l.length,function(t){for(var n,r=0;e>r;++r)s[(n=l[r]).i]=n.x(t);return s.join("")})}function xi(t,e){for(var n,r=is.interpolators.length;--r>=0&&!(n=is.interpolators[r](t,e)););return n}function wi(t,e){var n,r=[],i=[],o=t.length,a=e.length,s=Math.min(t.length,e.length);for(n=0;s>n;++n)r.push(xi(t[n],e[n]));for(;o>n;++n)i[n]=t[n];for(;a>n;++n)i[n]=e[n];return function(t){for(n=0;s>n;++n)i[n]=r[n](t);return i}}function Ci(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function Si(t){return function(e){return 1-t(1-e)}}function Ti(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function ki(t){return t*t}function _i(t){return t*t*t}function Mi(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,n=e*t;return 4*(.5>t?n:3*(t-e)+n-.75)}function Di(t){return function(e){return Math.pow(e,t)}}function Li(t){return 1-Math.cos(t*zs)}function Ai(t){return Math.pow(2,10*(t-1))}function Ni(t){return 1-Math.sqrt(1-t*t)}function Ei(t,e){var n;arguments.length<2&&(e=.45);arguments.length?n=e/Rs*Math.asin(1/t):(t=1,n=e/4);return function(r){return 1+t*Math.pow(2,-10*r)*Math.sin((r-n)*Rs/e)}}function ji(t){t||(t=1.70158);return function(e){return e*e*((t+1)*e-t)}}function Ii(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function Pi(t,e){t=is.hcl(t);e=is.hcl(e);var n=t.h,r=t.c,i=t.l,o=e.h-n,a=e.c-r,s=e.l-i;isNaN(a)&&(a=0,r=isNaN(r)?e.c:r);isNaN(o)?(o=0,n=isNaN(n)?e.h:n):o>180?o-=360:-180>o&&(o+=360);return function(t){return fe(n+o*t,r+a*t,i+s*t)+""}}function Hi(t,e){t=is.hsl(t);e=is.hsl(e);var n=t.h,r=t.s,i=t.l,o=e.h-n,a=e.s-r,s=e.l-i;isNaN(a)&&(a=0,r=isNaN(r)?e.s:r);isNaN(o)?(o=0,n=isNaN(n)?e.h:n):o>180?o-=360:-180>o&&(o+=360);return function(t){return ue(n+o*t,r+a*t,i+s*t)+""}}function Oi(t,e){t=is.lab(t);e=is.lab(e);var n=t.l,r=t.a,i=t.b,o=e.l-n,a=e.a-r,s=e.b-i;return function(t){return de(n+o*t,r+a*t,i+s*t)+""}}function Fi(t,e){e-=t;return function(n){return Math.round(t+e*n)}}function Ri(t){var e=[t.a,t.b],n=[t.c,t.d],r=zi(e),i=Wi(e,n),o=zi(qi(n,e,-i))||0;if(e[0]*n[1]<n[0]*e[1]){e[0]*=-1;e[1]*=-1;r*=-1;i*=-1}this.rotate=(r?Math.atan2(e[1],e[0]):Math.atan2(-n[0],n[1]))*Us;this.translate=[t.e,t.f];this.scale=[r,o];this.skew=o?Math.atan2(i,o)*Us:0}function Wi(t,e){return t[0]*e[0]+t[1]*e[1]}function zi(t){var e=Math.sqrt(Wi(t,t));if(e){t[0]/=e;t[1]/=e}return e}function qi(t,e,n){t[0]+=n*e[0];t[1]+=n*e[1];return t}function Ui(t,e){var n,r=[],i=[],o=is.transform(t),a=is.transform(e),s=o.translate,l=a.translate,u=o.rotate,c=a.rotate,f=o.skew,h=a.skew,d=o.scale,p=a.scale;if(s[0]!=l[0]||s[1]!=l[1]){r.push("translate(",null,",",null,")");i.push({i:1,x:yi(s[0],l[0])},{i:3,x:yi(s[1],l[1])})}else r.push(l[0]||l[1]?"translate("+l+")":"");if(u!=c){u-c>180?c+=360:c-u>180&&(u+=360);i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:yi(u,c)})}else c&&r.push(r.pop()+"rotate("+c+")");f!=h?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:yi(f,h)}):h&&r.push(r.pop()+"skewX("+h+")");if(d[0]!=p[0]||d[1]!=p[1]){n=r.push(r.pop()+"scale(",null,",",null,")");i.push({i:n-4,x:yi(d[0],p[0])},{i:n-2,x:yi(d[1],p[1])})}else(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")");n=i.length;return function(t){for(var e,o=-1;++o<n;)r[(e=i[o]).i]=e.x(t);return r.join("")}}function Bi(t,e){e=(e-=t=+t)||1/e;return function(n){return(n-t)/e}}function Vi(t,e){e=(e-=t=+t)||1/e;return function(n){return Math.max(0,Math.min(1,(n-t)/e))}}function Xi(t){for(var e=t.source,n=t.target,r=$i(e,n),i=[e];e!==r;){e=e.parent;i.push(e)}for(var o=i.length;n!==r;){i.splice(o,0,n);n=n.parent}return i}function Gi(t){for(var e=[],n=t.parent;null!=n;){e.push(t);t=n;n=n.parent}e.push(t);return e}function $i(t,e){if(t===e)return t;for(var n=Gi(t),r=Gi(e),i=n.pop(),o=r.pop(),a=null;i===o;){a=i;i=n.pop();o=r.pop()}return a}function Yi(t){t.fixed|=2}function Ji(t){t.fixed&=-7}function Ki(t){t.fixed|=4;t.px=t.x,t.py=t.y}function Zi(t){t.fixed&=-5}function Qi(t,e,n){var r=0,i=0;t.charge=0;if(!t.leaf)for(var o,a=t.nodes,s=a.length,l=-1;++l<s;){o=a[l];if(null!=o){Qi(o,e,n);t.charge+=o.charge;r+=o.charge*o.cx;i+=o.charge*o.cy}}if(t.point){if(!t.leaf){t.point.x+=Math.random()-.5;t.point.y+=Math.random()-.5}var u=e*n[t.point.index];t.charge+=t.pointCharge=u;r+=u*t.point.x;i+=u*t.point.y}t.cx=r/t.charge;t.cy=i/t.charge}function to(t,e){is.rebind(t,e,"sort","children","value");t.nodes=t;t.links=ao;return t}function eo(t,e){for(var n=[t];null!=(t=n.pop());){e(t);if((i=t.children)&&(r=i.length))for(var r,i;--r>=0;)n.push(i[r])}}function no(t,e){for(var n=[t],r=[];null!=(t=n.pop());){r.push(t);if((o=t.children)&&(i=o.length))for(var i,o,a=-1;++a<i;)n.push(o[a])}for(;null!=(t=r.pop());)e(t)}function ro(t){return t.children}function io(t){return t.value}function oo(t,e){return e.value-t.value}function ao(t){return is.merge(t.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}function so(t){return t.x}function lo(t){return t.y}function uo(t,e,n){t.y0=e;t.y=n}function co(t){return is.range(t.length)}function fo(t){for(var e=-1,n=t[0].length,r=[];++e<n;)r[e]=0;return r}function ho(t){for(var e,n=1,r=0,i=t[0][1],o=t.length;o>n;++n)if((e=t[n][1])>i){r=n;i=e}return r}function po(t){return t.reduce(go,0)}function go(t,e){return t+e[1]}function mo(t,e){return vo(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function vo(t,e){for(var n=-1,r=+t[0],i=(t[1]-r)/e,o=[];++n<=e;)o[n]=i*n+r;return o}function yo(t){return[is.min(t),is.max(t)]}function bo(t,e){return t.value-e.value}function xo(t,e){var n=t._pack_next;t._pack_next=e;e._pack_prev=t;e._pack_next=n;n._pack_prev=e}function wo(t,e){t._pack_next=e;e._pack_prev=t}function Co(t,e){var n=e.x-t.x,r=e.y-t.y,i=t.r+e.r;return.999*i*i>n*n+r*r}function So(t){function e(t){c=Math.min(t.x-t.r,c);f=Math.max(t.x+t.r,f);h=Math.min(t.y-t.r,h);d=Math.max(t.y+t.r,d)}if((n=t.children)&&(u=n.length)){var n,r,i,o,a,s,l,u,c=1/0,f=-1/0,h=1/0,d=-1/0;n.forEach(To);r=n[0];r.x=-r.r;r.y=0;e(r);if(u>1){i=n[1];i.x=i.r;i.y=0;e(i);if(u>2){o=n[2];Mo(r,i,o);e(o);xo(r,o);r._pack_prev=o;xo(o,i);i=r._pack_next;for(a=3;u>a;a++){Mo(r,i,o=n[a]);var p=0,g=1,m=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Co(s,o)){p=1;break}if(1==p)for(l=r._pack_prev;l!==s._pack_prev&&!Co(l,o);l=l._pack_prev,m++);if(p){m>g||g==m&&i.r<r.r?wo(r,i=s):wo(r=l,i);a--}else{xo(r,o);i=o;e(o)}}}}var v=(c+f)/2,y=(h+d)/2,b=0;for(a=0;u>a;a++){o=n[a];o.x-=v;o.y-=y;b=Math.max(b,o.r+Math.sqrt(o.x*o.x+o.y*o.y))}t.r=b;n.forEach(ko)}}function To(t){t._pack_next=t._pack_prev=t}function ko(t){delete t._pack_next;delete t._pack_prev}function _o(t,e,n,r){var i=t.children;t.x=e+=r*t.x;t.y=n+=r*t.y;t.r*=r;if(i)for(var o=-1,a=i.length;++o<a;)_o(i[o],e,n,r)}function Mo(t,e,n){var r=t.r+n.r,i=e.x-t.x,o=e.y-t.y;if(r&&(i||o)){var a=e.r+n.r,s=i*i+o*o;a*=a;r*=r;var l=.5+(r-a)/(2*s),u=Math.sqrt(Math.max(0,2*a*(r+s)-(r-=s)*r-a*a))/(2*s);n.x=t.x+l*i+u*o;n.y=t.y+l*o-u*i}else{n.x=t.x+r;n.y=t.y}}function Do(t,e){return t.parent==e.parent?1:2}function Lo(t){var e=t.children;return e.length?e[0]:t.t}function Ao(t){var e,n=t.children;return(e=n.length)?n[e-1]:t.t}function No(t,e,n){var r=n/(e.i-t.i);e.c-=r;e.s+=n;t.c+=r;e.z+=n;e.m+=n}function Eo(t){for(var e,n=0,r=0,i=t.children,o=i.length;--o>=0;){e=i[o];e.z+=n;e.m+=n;n+=e.s+(r+=e.c)}}function jo(t,e,n){return t.a.parent===e.parent?t.a:n}function Io(t){return 1+is.max(t,function(t){return t.y})}function Po(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ho(t){var e=t.children;return e&&e.length?Ho(e[0]):t}function Oo(t){var e,n=t.children;return n&&(e=n.length)?Oo(n[e-1]):t}function Fo(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Ro(t,e){var n=t.x+e[3],r=t.y+e[0],i=t.dx-e[1]-e[3],o=t.dy-e[0]-e[2];if(0>i){n+=i/2;i=0}if(0>o){r+=o/2;o=0}return{x:n,y:r,dx:i,dy:o}}function Wo(t){var e=t[0],n=t[t.length-1];return n>e?[e,n]:[n,e]}function zo(t){return t.rangeExtent?t.rangeExtent():Wo(t.range())}function qo(t,e,n,r){var i=n(t[0],t[1]),o=r(e[0],e[1]);return function(t){return o(i(t))}}function Uo(t,e){var n,r=0,i=t.length-1,o=t[r],a=t[i];if(o>a){n=r,r=i,i=n;n=o,o=a,a=n}t[r]=e.floor(o);t[i]=e.ceil(a);return t}function Bo(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Tu}function Vo(t,e,n,r){var i=[],o=[],a=0,s=Math.min(t.length,e.length)-1;if(t[s]<t[0]){t=t.slice().reverse();e=e.slice().reverse()}for(;++a<=s;){i.push(n(t[a-1],t[a]));o.push(r(e[a-1],e[a]))}return function(e){var n=is.bisect(t,e,1,s)-1;return o[n](i[n](e))}}function Xo(t,e,n,r){function i(){var i=Math.min(t.length,e.length)>2?Vo:qo,l=r?Vi:Bi;a=i(t,e,l,n);s=i(e,t,l,xi);return o}function o(t){return a(t)}var a,s;o.invert=function(t){return s(t)};o.domain=function(e){if(!arguments.length)return t;t=e.map(Number);return i()};o.range=function(t){if(!arguments.length)return e;e=t;return i()};o.rangeRound=function(t){return o.range(t).interpolate(Fi)};o.clamp=function(t){if(!arguments.length)return r;r=t;return i()};o.interpolate=function(t){if(!arguments.length)return n;n=t;return i()};o.ticks=function(e){return Jo(t,e)};o.tickFormat=function(e,n){return Ko(t,e,n)};o.nice=function(e){$o(t,e);return i()};o.copy=function(){return Xo(t,e,n,r)};return i()}function Go(t,e){return is.rebind(t,e,"range","rangeRound","interpolate","clamp")}function $o(t,e){return Uo(t,Bo(Yo(t,e)[2]))}function Yo(t,e){null==e&&(e=10);var n=Wo(t),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/e)/Math.LN10)),o=e/r*i;.15>=o?i*=10:.35>=o?i*=5:.75>=o&&(i*=2);n[0]=Math.ceil(n[0]/i)*i;n[1]=Math.floor(n[1]/i)*i+.5*i;n[2]=i;return n}function Jo(t,e){return is.range.apply(is,Yo(t,e))}function Ko(t,e,n){var r=Yo(t,e);if(n){var i=hl.exec(n);i.shift();if("s"===i[8]){var o=is.formatPrefix(Math.max(ys(r[0]),ys(r[1])));i[7]||(i[7]="."+Zo(o.scale(r[2])));i[8]="f";n=is.format(i.join(""));return function(t){return n(o.scale(t))+o.symbol}}i[7]||(i[7]="."+Qo(i[8],r));n=i.join("")}else n=",."+Zo(r[2])+"f";return is.format(n)}function Zo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function Qo(t,e){var n=Zo(e[2]);return t in ku?Math.abs(n-Zo(Math.max(ys(e[0]),ys(e[1]))))+ +("e"!==t):n-2*("%"===t)}function ta(t,e,n,r){function i(t){return(n?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function o(t){return n?Math.pow(e,t):-Math.pow(e,-t)}function a(e){return t(i(e))}a.invert=function(e){return o(t.invert(e))};a.domain=function(e){if(!arguments.length)return r;n=e[0]>=0;t.domain((r=e.map(Number)).map(i));return a};a.base=function(n){if(!arguments.length)return e;e=+n;t.domain(r.map(i));return a};a.nice=function(){var e=Uo(r.map(i),n?Math:Mu);t.domain(e);r=e.map(o);return a};a.ticks=function(){var t=Wo(r),a=[],s=t[0],l=t[1],u=Math.floor(i(s)),c=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(c-u)){if(n){for(;c>u;u++)for(var h=1;f>h;h++)a.push(o(u)*h);a.push(o(u))}else{a.push(o(u));for(;u++<c;)for(var h=f-1;h>0;h--)a.push(o(u)*h)}for(u=0;a[u]<s;u++);for(c=a.length;a[c-1]>l;c--);a=a.slice(u,c)}return a};a.tickFormat=function(t,e){if(!arguments.length)return _u;arguments.length<2?e=_u:"function"!=typeof e&&(e=is.format(e));var r,s=Math.max(.1,t/a.ticks().length),l=n?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(t){return t/o(l(i(t)+r))<=s?e(t):""}};a.copy=function(){return ta(t.copy(),e,n,r)};return Go(a,t)}function ea(t,e,n){function r(e){return t(i(e))}var i=na(e),o=na(1/e);r.invert=function(e){return o(t.invert(e))};r.domain=function(e){if(!arguments.length)return n;t.domain((n=e.map(Number)).map(i));return r};r.ticks=function(t){return Jo(n,t)};r.tickFormat=function(t,e){return Ko(n,t,e)};r.nice=function(t){return r.domain($o(n,t))};r.exponent=function(a){if(!arguments.length)return e;i=na(e=a);o=na(1/e);t.domain(n.map(i));return r};r.copy=function(){return ea(t.copy(),e,n)};return Go(r,t)}function na(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function ra(t,e){function n(n){return o[((i.get(n)||("range"===e.t?i.set(n,t.push(n)):0/0))-1)%o.length]}function r(e,n){return is.range(t.length).map(function(t){return e+n*t})}var i,o,a;n.domain=function(r){if(!arguments.length)return t;t=[];i=new u;for(var o,a=-1,s=r.length;++a<s;)i.has(o=r[a])||i.set(o,t.push(o));return n[e.t].apply(n,e.a)};n.range=function(t){if(!arguments.length)return o;o=t;a=0;e={t:"range",a:arguments};return n};n.rangePoints=function(i,s){arguments.length<2&&(s=0);var l=i[0],u=i[1],c=t.length<2?(l=(l+u)/2,0):(u-l)/(t.length-1+s);o=r(l+c*s/2,c);a=0;e={t:"rangePoints",a:arguments};return n};n.rangeRoundPoints=function(i,s){arguments.length<2&&(s=0);var l=i[0],u=i[1],c=t.length<2?(l=u=Math.round((l+u)/2),0):(u-l)/(t.length-1+s)|0;o=r(l+Math.round(c*s/2+(u-l-(t.length-1+s)*c)/2),c);a=0;e={t:"rangeRoundPoints",a:arguments};return n};n.rangeBands=function(i,s,l){arguments.length<2&&(s=0);arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],f=i[1-u],h=(f-c)/(t.length-s+2*l);o=r(c+h*l,h);u&&o.reverse();a=h*(1-s);e={t:"rangeBands",a:arguments};return n};n.rangeRoundBands=function(i,s,l){arguments.length<2&&(s=0);arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],f=i[1-u],h=Math.floor((f-c)/(t.length-s+2*l));o=r(c+Math.round((f-c-(t.length-s)*h)/2),h);u&&o.reverse();a=Math.round(h*(1-s));e={t:"rangeRoundBands",a:arguments};return n};n.rangeBand=function(){return a};n.rangeExtent=function(){return Wo(e.a[0])};n.copy=function(){return ra(t,e)};return n.domain(t)}function ia(t,n){function o(){var e=0,r=n.length;s=[];for(;++e<r;)s[e-1]=is.quantile(t,e/r);return a}function a(t){return isNaN(t=+t)?void 0:n[is.bisect(s,t)]}var s;a.domain=function(n){if(!arguments.length)return t;t=n.map(r).filter(i).sort(e);return o()};a.range=function(t){if(!arguments.length)return n;n=t;return o()};a.quantiles=function(){return s};a.invertExtent=function(e){e=n.indexOf(e);return 0>e?[0/0,0/0]:[e>0?s[e-1]:t[0],e<s.length?s[e]:t[t.length-1]]};a.copy=function(){return ia(t,n)};return o()}function oa(t,e,n){function r(e){return n[Math.max(0,Math.min(a,Math.floor(o*(e-t))))]}function i(){o=n.length/(e-t);a=n.length-1;return r}var o,a;r.domain=function(n){if(!arguments.length)return[t,e];t=+n[0];e=+n[n.length-1];return i()};r.range=function(t){if(!arguments.length)return n;n=t;return i()};r.invertExtent=function(e){e=n.indexOf(e);e=0>e?0/0:e/o+t;return[e,e+1/o]};r.copy=function(){return oa(t,e,n)};return i()}function aa(t,e){function n(n){return n>=n?e[is.bisect(t,n)]:void 0}n.domain=function(e){if(!arguments.length)return t;t=e;return n};n.range=function(t){if(!arguments.length)return e;e=t;return n};n.invertExtent=function(n){n=e.indexOf(n);return[t[n-1],t[n]]};n.copy=function(){return aa(t,e)};return n}function sa(t){function e(t){return+t}e.invert=e;e.domain=e.range=function(n){if(!arguments.length)return t;t=n.map(e);return e};e.ticks=function(e){return Jo(t,e)};e.tickFormat=function(e,n){return Ko(t,e,n)};e.copy=function(){return sa(t)};return e}function la(){return 0}function ua(t){return t.innerRadius}function ca(t){return t.outerRadius}function fa(t){return t.startAngle}function ha(t){return t.endAngle}function da(t){return t&&t.padAngle}function pa(t,e,n,r){return(t-n)*e-(e-r)*t>0?0:1}function ga(t,e,n,r,i){var o=t[0]-e[0],a=t[1]-e[1],s=(i?r:-r)/Math.sqrt(o*o+a*a),l=s*a,u=-s*o,c=t[0]+l,f=t[1]+u,h=e[0]+l,d=e[1]+u,p=(c+h)/2,g=(f+d)/2,m=h-c,v=d-f,y=m*m+v*v,b=n-r,x=c*d-h*f,w=(0>v?-1:1)*Math.sqrt(b*b*y-x*x),C=(x*v-m*w)/y,S=(-x*m-v*w)/y,T=(x*v+m*w)/y,k=(-x*m+v*w)/y,_=C-p,M=S-g,D=T-p,L=k-g;_*_+M*M>D*D+L*L&&(C=T,S=k);return[[C-l,S-u],[C*n/b,S*n/b]]}function ma(t){function e(e){function a(){u.push("M",o(t(c),s))}for(var l,u=[],c=[],f=-1,h=e.length,d=Me(n),p=Me(r);++f<h;)if(i.call(this,l=e[f],f))c.push([+d.call(this,l,f),+p.call(this,l,f)]);else if(c.length){a();c=[]}c.length&&a();return u.length?u.join(""):null}var n=Ar,r=Nr,i=Nn,o=va,a=o.key,s=.7;e.x=function(t){if(!arguments.length)return n;n=t;return e};e.y=function(t){if(!arguments.length)return r;r=t;return e};e.defined=function(t){if(!arguments.length)return i;i=t;return e};e.interpolate=function(t){if(!arguments.length)return a;a="function"==typeof t?o=t:(o=ju.get(t)||va).key;return e};e.tension=function(t){if(!arguments.length)return s;s=t;return e};return e}function va(t){return t.join("L")}function ya(t){return va(t)+"Z"}function ba(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("H",(r[0]+(r=t[e])[0])/2,"V",r[1]);n>1&&i.push("H",r[0]);return i.join("")}function xa(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("V",(r=t[e])[1],"H",r[0]);return i.join("")}function wa(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("H",(r=t[e])[0],"V",r[1]);return i.join("")}function Ca(t,e){return t.length<4?va(t):t[1]+ka(t.slice(1,-1),_a(t,e))}function Sa(t,e){return t.length<3?va(t):t[0]+ka((t.push(t[0]),t),_a([t[t.length-2]].concat(t,[t[1]]),e))}function Ta(t,e){return t.length<3?va(t):t[0]+ka(t,_a(t,e))}function ka(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return va(t);var n=t.length!=e.length,r="",i=t[0],o=t[1],a=e[0],s=a,l=1;if(n){r+="Q"+(o[0]-2*a[0]/3)+","+(o[1]-2*a[1]/3)+","+o[0]+","+o[1];i=t[1];l=2}if(e.length>1){s=e[1];o=t[l];l++;r+="C"+(i[0]+a[0])+","+(i[1]+a[1])+","+(o[0]-s[0])+","+(o[1]-s[1])+","+o[0]+","+o[1];for(var u=2;u<e.length;u++,l++){o=t[l];s=e[u];r+="S"+(o[0]-s[0])+","+(o[1]-s[1])+","+o[0]+","+o[1]}}if(n){var c=t[l];r+="Q"+(o[0]+2*s[0]/3)+","+(o[1]+2*s[1]/3)+","+c[0]+","+c[1]}return r}function _a(t,e){for(var n,r=[],i=(1-e)/2,o=t[0],a=t[1],s=1,l=t.length;++s<l;){n=o;o=a;a=t[s];r.push([i*(a[0]-n[0]),i*(a[1]-n[1])])}return r}function Ma(t){if(t.length<3)return va(t);var e=1,n=t.length,r=t[0],i=r[0],o=r[1],a=[i,i,i,(r=t[1])[0]],s=[o,o,o,r[1]],l=[i,",",o,"L",Na(Hu,a),",",Na(Hu,s)];t.push(t[n-1]);for(;++e<=n;){r=t[e];a.shift();a.push(r[0]);s.shift();s.push(r[1]);Ea(l,a,s)}t.pop();l.push("L",r);return l.join("")}function Da(t){if(t.length<4)return va(t);for(var e,n=[],r=-1,i=t.length,o=[0],a=[0];++r<3;){e=t[r];o.push(e[0]);a.push(e[1])}n.push(Na(Hu,o)+","+Na(Hu,a));--r;for(;++r<i;){e=t[r];o.shift();o.push(e[0]);a.shift();a.push(e[1]);Ea(n,o,a)}return n.join("")}function La(t){for(var e,n,r=-1,i=t.length,o=i+4,a=[],s=[];++r<4;){n=t[r%i];a.push(n[0]);s.push(n[1])}e=[Na(Hu,a),",",Na(Hu,s)];--r;for(;++r<o;){n=t[r%i];a.shift();a.push(n[0]);s.shift();s.push(n[1]);Ea(e,a,s)}return e.join("")}function Aa(t,e){var n=t.length-1;if(n)for(var r,i,o=t[0][0],a=t[0][1],s=t[n][0]-o,l=t[n][1]-a,u=-1;++u<=n;){r=t[u];i=u/n;r[0]=e*r[0]+(1-e)*(o+i*s);r[1]=e*r[1]+(1-e)*(a+i*l)}return Ma(t)}function Na(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Ea(t,e,n){t.push("C",Na(Iu,e),",",Na(Iu,n),",",Na(Pu,e),",",Na(Pu,n),",",Na(Hu,e),",",Na(Hu,n))}function ja(t,e){return(e[1]-t[1])/(e[0]-t[0])}function Ia(t){for(var e=0,n=t.length-1,r=[],i=t[0],o=t[1],a=r[0]=ja(i,o);++e<n;)r[e]=(a+(a=ja(i=o,o=t[e+1])))/2;r[e]=a;return r}function Pa(t){for(var e,n,r,i,o=[],a=Ia(t),s=-1,l=t.length-1;++s<l;){e=ja(t[s],t[s+1]);if(ys(e)<Hs)a[s]=a[s+1]=0;else{n=a[s]/e;r=a[s+1]/e;i=n*n+r*r;if(i>9){i=3*e/Math.sqrt(i);a[s]=i*n;a[s+1]=i*r}}}s=-1;for(;++s<=l;){i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+a[s]*a[s]));o.push([i||0,a[s]*i||0])}return o}function Ha(t){return t.length<3?va(t):t[0]+ka(t,Pa(t))}function Oa(t){for(var e,n,r,i=-1,o=t.length;++i<o;){e=t[i];n=e[0];r=e[1]-zs;e[0]=n*Math.cos(r);e[1]=n*Math.sin(r)}return t}function Fa(t){function e(e){function l(){g.push("M",s(t(v),f),c,u(t(m.reverse()),f),"Z") }for(var h,d,p,g=[],m=[],v=[],y=-1,b=e.length,x=Me(n),w=Me(i),C=n===r?function(){return d}:Me(r),S=i===o?function(){return p}:Me(o);++y<b;)if(a.call(this,h=e[y],y)){m.push([d=+x.call(this,h,y),p=+w.call(this,h,y)]);v.push([+C.call(this,h,y),+S.call(this,h,y)])}else if(m.length){l();m=[];v=[]}m.length&&l();return g.length?g.join(""):null}var n=Ar,r=Ar,i=0,o=Nr,a=Nn,s=va,l=s.key,u=s,c="L",f=.7;e.x=function(t){if(!arguments.length)return r;n=r=t;return e};e.x0=function(t){if(!arguments.length)return n;n=t;return e};e.x1=function(t){if(!arguments.length)return r;r=t;return e};e.y=function(t){if(!arguments.length)return o;i=o=t;return e};e.y0=function(t){if(!arguments.length)return i;i=t;return e};e.y1=function(t){if(!arguments.length)return o;o=t;return e};e.defined=function(t){if(!arguments.length)return a;a=t;return e};e.interpolate=function(t){if(!arguments.length)return l;l="function"==typeof t?s=t:(s=ju.get(t)||va).key;u=s.reverse||s;c=s.closed?"M":"L";return e};e.tension=function(t){if(!arguments.length)return f;f=t;return e};return e}function Ra(t){return t.radius}function Wa(t){return[t.x,t.y]}function za(t){return function(){var e=t.apply(this,arguments),n=e[0],r=e[1]-zs;return[n*Math.cos(r),n*Math.sin(r)]}}function qa(){return 64}function Ua(){return"circle"}function Ba(t){var e=Math.sqrt(t/Fs);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}function Va(t){return function(){var e,n;if((e=this[t])&&(n=e[e.active])){if(--e.count){delete e[e.active];e.active+=.5}else delete this[t];n.event&&n.event.interrupt.call(this,this.__data__,n.index)}}}function Xa(t,e,n){Ss(t,Uu);t.namespace=e;t.id=n;return t}function Ga(t,e,n,r){var i=t.id,o=t.namespace;return q(t,"function"==typeof n?function(t,a,s){t[o][i].tween.set(e,r(n.call(t,t.__data__,a,s)))}:(n=r(n),function(t){t[o][i].tween.set(e,n)}))}function $a(t){null==t&&(t="");return function(){this.textContent=t}}function Ya(t){return null==t?"__transition__":"__transition_"+t+"__"}function Ja(t,e,n,r,i){var o=t[n]||(t[n]={active:0,count:0}),a=o[r];if(!a){var s=i.time;a=o[r]={tween:new u,time:s,delay:i.delay,duration:i.duration,ease:i.ease,index:e};i=null;++o.count;is.timer(function(i){function l(n){if(o.active>r)return c();var i=o[o.active];if(i){--o.count;delete o[o.active];i.event&&i.event.interrupt.call(t,t.__data__,i.index)}o.active=r;a.event&&a.event.start.call(t,t.__data__,e);a.tween.forEach(function(n,r){(r=r.call(t,t.__data__,e))&&g.push(r)});h=a.ease;f=a.duration;is.timer(function(){p.c=u(n||1)?Nn:u;return 1},0,s)}function u(n){if(o.active!==r)return 1;for(var i=n/f,s=h(i),l=g.length;l>0;)g[--l].call(t,s);if(i>=1){a.event&&a.event.end.call(t,t.__data__,e);return c()}}function c(){--o.count?delete o[r]:delete t[n];return 1}var f,h,d=a.delay,p=ul,g=[];p.t=d+s;if(i>=d)return l(i-d);p.c=l;return void 0},0,s)}}function Ka(t,e,n){t.attr("transform",function(t){var r=e(t);return"translate("+(isFinite(r)?r:n(t))+",0)"})}function Za(t,e,n){t.attr("transform",function(t){var r=e(t);return"translate(0,"+(isFinite(r)?r:n(t))+")"})}function Qa(t){return t.toISOString()}function ts(t,e,n){function r(e){return t(e)}function i(t,n){var r=t[1]-t[0],i=r/n,o=is.bisect(Zu,i);return o==Zu.length?[e.year,Yo(t.map(function(t){return t/31536e6}),n)[2]]:o?e[i/Zu[o-1]<Zu[o]/i?o-1:o]:[ec,Yo(t,n)[2]]}r.invert=function(e){return es(t.invert(e))};r.domain=function(e){if(!arguments.length)return t.domain().map(es);t.domain(e);return r};r.nice=function(t,e){function n(n){return!isNaN(n)&&!t.range(n,es(+n+1),e).length}var o=r.domain(),a=Wo(o),s=null==t?i(a,10):"number"==typeof t&&i(a,t);s&&(t=s[0],e=s[1]);return r.domain(Uo(o,e>1?{floor:function(e){for(;n(e=t.floor(e));)e=es(e-1);return e},ceil:function(e){for(;n(e=t.ceil(e));)e=es(+e+1);return e}}:t))};r.ticks=function(t,e){var n=Wo(r.domain()),o=null==t?i(n,10):"number"==typeof t?i(n,t):!t.range&&[{range:t},e];o&&(t=o[0],e=o[1]);return t.range(n[0],es(+n[1]+1),1>e?1:e)};r.tickFormat=function(){return n};r.copy=function(){return ts(t.copy(),e,n)};return Go(r,t)}function es(t){return new Date(t)}function ns(t){return JSON.parse(t.responseText)}function rs(t){var e=ss.createRange();e.selectNode(ss.body);return e.createContextualFragment(t.responseText)}var is={version:"3.5.2"};Date.now||(Date.now=function(){return+new Date});var os=[].slice,as=function(t){return os.call(t)},ss=document,ls=ss.documentElement,us=window;try{as(ls.childNodes)[0].nodeType}catch(cs){as=function(t){for(var e=t.length,n=new Array(e);e--;)n[e]=t[e];return n}}try{ss.createElement("div").style.setProperty("opacity",0,"")}catch(fs){var hs=us.Element.prototype,ds=hs.setAttribute,ps=hs.setAttributeNS,gs=us.CSSStyleDeclaration.prototype,ms=gs.setProperty;hs.setAttribute=function(t,e){ds.call(this,t,e+"")};hs.setAttributeNS=function(t,e,n){ps.call(this,t,e,n+"")};gs.setProperty=function(t,e,n){ms.call(this,t,e+"",n)}}is.ascending=e;is.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:0/0};is.min=function(t,e){var n,r,i=-1,o=t.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=t[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=t[i])&&n>r&&(n=r)}else{for(;++i<o;)if(null!=(r=e.call(t,t[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=e.call(t,t[i],i))&&n>r&&(n=r)}return n};is.max=function(t,e){var n,r,i=-1,o=t.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=t[i])&&r>=r){n=r;break}for(;++i<o;)null!=(r=t[i])&&r>n&&(n=r)}else{for(;++i<o;)if(null!=(r=e.call(t,t[i],i))&&r>=r){n=r;break}for(;++i<o;)null!=(r=e.call(t,t[i],i))&&r>n&&(n=r)}return n};is.extent=function(t,e){var n,r,i,o=-1,a=t.length;if(1===arguments.length){for(;++o<a;)if(null!=(r=t[o])&&r>=r){n=i=r;break}for(;++o<a;)if(null!=(r=t[o])){n>r&&(n=r);r>i&&(i=r)}}else{for(;++o<a;)if(null!=(r=e.call(t,t[o],o))&&r>=r){n=i=r;break}for(;++o<a;)if(null!=(r=e.call(t,t[o],o))){n>r&&(n=r);r>i&&(i=r)}}return[n,i]};is.sum=function(t,e){var n,r=0,o=t.length,a=-1;if(1===arguments.length)for(;++a<o;)i(n=+t[a])&&(r+=n);else for(;++a<o;)i(n=+e.call(t,t[a],a))&&(r+=n);return r};is.mean=function(t,e){var n,o=0,a=t.length,s=-1,l=a;if(1===arguments.length)for(;++s<a;)i(n=r(t[s]))?o+=n:--l;else for(;++s<a;)i(n=r(e.call(t,t[s],s)))?o+=n:--l;return l?o/l:void 0};is.quantile=function(t,e){var n=(t.length-1)*e+1,r=Math.floor(n),i=+t[r-1],o=n-r;return o?i+o*(t[r]-i):i};is.median=function(t,n){var o,a=[],s=t.length,l=-1;if(1===arguments.length)for(;++l<s;)i(o=r(t[l]))&&a.push(o);else for(;++l<s;)i(o=r(n.call(t,t[l],l)))&&a.push(o);return a.length?is.quantile(a.sort(e),.5):void 0};is.variance=function(t,e){var n,o,a=t.length,s=0,l=0,u=-1,c=0;if(1===arguments.length){for(;++u<a;)if(i(n=r(t[u]))){o=n-s;s+=o/++c;l+=o*(n-s)}}else for(;++u<a;)if(i(n=r(e.call(t,t[u],u)))){o=n-s;s+=o/++c;l+=o*(n-s)}return c>1?l/(c-1):void 0};is.deviation=function(){var t=is.variance.apply(this,arguments);return t?Math.sqrt(t):t};var vs=o(e);is.bisectLeft=vs.left;is.bisect=is.bisectRight=vs.right;is.bisector=function(t){return o(1===t.length?function(n,r){return e(t(n),r)}:t)};is.shuffle=function(t,e,n){if((o=arguments.length)<3){n=t.length;2>o&&(e=0)}for(var r,i,o=n-e;o;){i=Math.random()*o--|0;r=t[o+e],t[o+e]=t[i+e],t[i+e]=r}return t};is.permute=function(t,e){for(var n=e.length,r=new Array(n);n--;)r[n]=t[e[n]];return r};is.pairs=function(t){for(var e,n=0,r=t.length-1,i=t[0],o=new Array(0>r?0:r);r>n;)o[n]=[e=i,i=t[++n]];return o};is.zip=function(){if(!(r=arguments.length))return[];for(var t=-1,e=is.min(arguments,a),n=new Array(e);++t<e;)for(var r,i=-1,o=n[t]=new Array(r);++i<r;)o[i]=arguments[i][t];return n};is.transpose=function(t){return is.zip.apply(is,t)};is.keys=function(t){var e=[];for(var n in t)e.push(n);return e};is.values=function(t){var e=[];for(var n in t)e.push(t[n]);return e};is.entries=function(t){var e=[];for(var n in t)e.push({key:n,value:t[n]});return e};is.merge=function(t){for(var e,n,r,i=t.length,o=-1,a=0;++o<i;)a+=t[o].length;n=new Array(a);for(;--i>=0;){r=t[i];e=r.length;for(;--e>=0;)n[--a]=r[e]}return n};var ys=Math.abs;is.range=function(t,e,n){if(arguments.length<3){n=1;if(arguments.length<2){e=t;t=0}}if((e-t)/n===1/0)throw new Error("infinite range");var r,i=[],o=s(ys(n)),a=-1;t*=o,e*=o,n*=o;if(0>n)for(;(r=t+n*++a)>e;)i.push(r/o);else for(;(r=t+n*++a)<e;)i.push(r/o);return i};is.map=function(t,e){var n=new u;if(t instanceof u)t.forEach(function(t,e){n.set(t,e)});else if(Array.isArray(t)){var r,i=-1,o=t.length;if(1===arguments.length)for(;++i<o;)n.set(i,t[i]);else for(;++i<o;)n.set(e.call(t,r=t[i],i),r)}else for(var a in t)n.set(a,t[a]);return n};var bs="__proto__",xs="\x00";l(u,{has:h,get:function(t){return this._[c(t)]},set:function(t,e){return this._[c(t)]=e},remove:d,keys:p,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:f(e),value:this._[e]});return t},size:g,empty:m,forEach:function(t){for(var e in this._)t.call(this,f(e),this._[e])}});is.nest=function(){function t(e,a,s){if(s>=o.length)return r?r.call(i,a):n?a.sort(n):a;for(var l,c,f,h,d=-1,p=a.length,g=o[s++],m=new u;++d<p;)(h=m.get(l=g(c=a[d])))?h.push(c):m.set(l,[c]);if(e){c=e();f=function(n,r){c.set(n,t(e,r,s))}}else{c={};f=function(n,r){c[n]=t(e,r,s)}}m.forEach(f);return c}function e(t,n){if(n>=o.length)return t;var r=[],i=a[n++];t.forEach(function(t,i){r.push({key:t,values:e(i,n)})});return i?r.sort(function(t,e){return i(t.key,e.key)}):r}var n,r,i={},o=[],a=[];i.map=function(e,n){return t(n,e,0)};i.entries=function(n){return e(t(is.map,n,0),0)};i.key=function(t){o.push(t);return i};i.sortKeys=function(t){a[o.length-1]=t;return i};i.sortValues=function(t){n=t;return i};i.rollup=function(t){r=t;return i};return i};is.set=function(t){var e=new v;if(t)for(var n=0,r=t.length;r>n;++n)e.add(t[n]);return e};l(v,{has:h,add:function(t){this._[c(t+="")]=!0;return t},remove:d,values:p,size:g,empty:m,forEach:function(t){for(var e in this._)t.call(this,f(e))}});is.behavior={};is.rebind=function(t,e){for(var n,r=1,i=arguments.length;++r<i;)t[n=arguments[r]]=y(t,e,e[n]);return t};var ws=["webkit","ms","moz","Moz","o","O"];is.dispatch=function(){for(var t=new w,e=-1,n=arguments.length;++e<n;)t[arguments[e]]=C(t);return t};w.prototype.on=function(t,e){var n=t.indexOf("."),r="";if(n>=0){r=t.slice(n+1);t=t.slice(0,n)}if(t)return arguments.length<2?this[t].on(r):this[t].on(r,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(r,null);return this}};is.event=null;is.requote=function(t){return t.replace(Cs,"\\$&")};var Cs=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Ss={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var n in e)t[n]=e[n]},Ts=function(t,e){return e.querySelector(t)},ks=function(t,e){return e.querySelectorAll(t)},_s=ls.matches||ls[b(ls,"matchesSelector")],Ms=function(t,e){return _s.call(t,e)};if("function"==typeof Sizzle){Ts=function(t,e){return Sizzle(t,e)[0]||null};ks=Sizzle;Ms=Sizzle.matchesSelector}is.selection=function(){return Ns};var Ds=is.selection.prototype=[];Ds.select=function(t){var e,n,r,i,o=[];t=M(t);for(var a=-1,s=this.length;++a<s;){o.push(e=[]);e.parentNode=(r=this[a]).parentNode;for(var l=-1,u=r.length;++l<u;)if(i=r[l]){e.push(n=t.call(i,i.__data__,l,a));n&&"__data__"in i&&(n.__data__=i.__data__)}else e.push(null)}return _(o)};Ds.selectAll=function(t){var e,n,r=[];t=D(t);for(var i=-1,o=this.length;++i<o;)for(var a=this[i],s=-1,l=a.length;++s<l;)if(n=a[s]){r.push(e=as(t.call(n,n.__data__,s,i)));e.parentNode=n}return _(r)};var Ls={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};is.ns={prefix:Ls,qualify:function(t){var e=t.indexOf(":"),n=t;if(e>=0){n=t.slice(0,e);t=t.slice(e+1)}return Ls.hasOwnProperty(n)?{space:Ls[n],local:t}:t}};Ds.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node();t=is.ns.qualify(t);return t.local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(e in t)this.each(L(e,t[e]));return this}return this.each(L(t,e))};Ds.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node(),r=(t=E(t)).length,i=-1;if(e=n.classList){for(;++i<r;)if(!e.contains(t[i]))return!1}else{e=n.getAttribute("class");for(;++i<r;)if(!N(t[i]).test(e))return!1}return!0}for(e in t)this.each(j(e,t[e]));return this}return this.each(j(t,e))};Ds.style=function(t,e,n){var r=arguments.length;if(3>r){if("string"!=typeof t){2>r&&(e="");for(n in t)this.each(P(n,t[n],e));return this}if(2>r)return us.getComputedStyle(this.node(),null).getPropertyValue(t);n=""}return this.each(P(t,e,n))};Ds.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(H(e,t[e]));return this}return this.each(H(t,e))};Ds.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent};Ds.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML};Ds.append=function(t){t=O(t);return this.select(function(){return this.appendChild(t.apply(this,arguments))})};Ds.insert=function(t,e){t=O(t);e=M(e);return this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})};Ds.remove=function(){return this.each(F)};Ds.data=function(t,e){function n(t,n){var r,i,o,a=t.length,f=n.length,h=Math.min(a,f),d=new Array(f),p=new Array(f),g=new Array(a);if(e){var m,v=new u,y=new Array(a);for(r=-1;++r<a;){v.has(m=e.call(i=t[r],i.__data__,r))?g[r]=i:v.set(m,i);y[r]=m}for(r=-1;++r<f;){if(i=v.get(m=e.call(n,o=n[r],r))){if(i!==!0){d[r]=i;i.__data__=o}}else p[r]=R(o);v.set(m,!0)}for(r=-1;++r<a;)v.get(y[r])!==!0&&(g[r]=t[r])}else{for(r=-1;++r<h;){i=t[r];o=n[r];if(i){i.__data__=o;d[r]=i}else p[r]=R(o)}for(;f>r;++r)p[r]=R(n[r]);for(;a>r;++r)g[r]=t[r]}p.update=d;p.parentNode=d.parentNode=g.parentNode=t.parentNode;s.push(p);l.push(d);c.push(g)}var r,i,o=-1,a=this.length;if(!arguments.length){t=new Array(a=(r=this[0]).length);for(;++o<a;)(i=r[o])&&(t[o]=i.__data__);return t}var s=U([]),l=_([]),c=_([]);if("function"==typeof t)for(;++o<a;)n(r=this[o],t.call(r,r.parentNode.__data__,o));else for(;++o<a;)n(r=this[o],t);l.enter=function(){return s};l.exit=function(){return c};return l};Ds.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")};Ds.filter=function(t){var e,n,r,i=[];"function"!=typeof t&&(t=W(t));for(var o=0,a=this.length;a>o;o++){i.push(e=[]);e.parentNode=(n=this[o]).parentNode;for(var s=0,l=n.length;l>s;s++)(r=n[s])&&t.call(r,r.__data__,s,o)&&e.push(r)}return _(i)};Ds.order=function(){for(var t=-1,e=this.length;++t<e;)for(var n,r=this[t],i=r.length-1,o=r[i];--i>=0;)if(n=r[i]){o&&o!==n.nextSibling&&o.parentNode.insertBefore(n,o);o=n}return this};Ds.sort=function(t){t=z.apply(this,arguments);for(var e=-1,n=this.length;++e<n;)this[e].sort(t);return this.order()};Ds.each=function(t){return q(this,function(e,n,r){t.call(e,e.__data__,n,r)})};Ds.call=function(t){var e=as(arguments);t.apply(e[0]=this,e);return this};Ds.empty=function(){return!this.node()};Ds.node=function(){for(var t=0,e=this.length;e>t;t++)for(var n=this[t],r=0,i=n.length;i>r;r++){var o=n[r];if(o)return o}return null};Ds.size=function(){var t=0;q(this,function(){++t});return t};var As=[];is.selection.enter=U;is.selection.enter.prototype=As;As.append=Ds.append;As.empty=Ds.empty;As.node=Ds.node;As.call=Ds.call;As.size=Ds.size;As.select=function(t){for(var e,n,r,i,o,a=[],s=-1,l=this.length;++s<l;){r=(i=this[s]).update;a.push(e=[]);e.parentNode=i.parentNode;for(var u=-1,c=i.length;++u<c;)if(o=i[u]){e.push(r[u]=n=t.call(i.parentNode,o.__data__,u,s));n.__data__=o.__data__}else e.push(null)}return _(a)};As.insert=function(t,e){arguments.length<2&&(e=B(this));return Ds.insert.call(this,t,e)};is.select=function(t){var e=["string"==typeof t?Ts(t,ss):t];e.parentNode=ls;return _([e])};is.selectAll=function(t){var e=as("string"==typeof t?ks(t,ss):t);e.parentNode=ls;return _([e])};var Ns=is.select(ls);Ds.on=function(t,e,n){var r=arguments.length;if(3>r){if("string"!=typeof t){2>r&&(e=!1);for(n in t)this.each(V(n,t[n],e));return this}if(2>r)return(r=this.node()["__on"+t])&&r._;n=!1}return this.each(V(t,e,n))};var Es=is.map({mouseenter:"mouseover",mouseleave:"mouseout"});Es.forEach(function(t){"on"+t in ss&&Es.remove(t)});var js="onselectstart"in ss?null:b(ls.style,"userSelect"),Is=0;is.mouse=function(t){return Y(t,T())};var Ps=/WebKit/.test(us.navigator.userAgent)?-1:0;is.touch=function(t,e,n){arguments.length<3&&(n=e,e=T().changedTouches);if(e)for(var r,i=0,o=e.length;o>i;++i)if((r=e[i]).identifier===n)return Y(t,r)};is.behavior.drag=function(){function t(){this.on("mousedown.drag",i).on("touchstart.drag",o)}function e(t,e,i,o,a){return function(){function s(){var t,n,r=e(h,g);if(r){t=r[0]-b[0];n=r[1]-b[1];p|=t|n;b=r;d({type:"drag",x:r[0]+u[0],y:r[1]+u[1],dx:t,dy:n})}}function l(){if(e(h,g)){v.on(o+m,null).on(a+m,null);y(p&&is.event.target===f);d({type:"dragend"})}}var u,c=this,f=is.event.target,h=c.parentNode,d=n.of(c,arguments),p=0,g=t(),m=".drag"+(null==g?"":"-"+g),v=is.select(i()).on(o+m,s).on(a+m,l),y=$(),b=e(h,g);if(r){u=r.apply(c,arguments);u=[u.x-b[0],u.y-b[1]]}else u=[0,0];d({type:"dragstart"})}}var n=k(t,"drag","dragstart","dragend"),r=null,i=e(x,is.mouse,Z,"mousemove","mouseup"),o=e(J,is.touch,K,"touchmove","touchend");t.origin=function(e){if(!arguments.length)return r;r=e;return t};return is.rebind(t,n,"on")};is.touches=function(t,e){arguments.length<2&&(e=T().touches);return e?as(e).map(function(e){var n=Y(t,e);n.identifier=e.identifier;return n}):[]};var Hs=1e-6,Os=Hs*Hs,Fs=Math.PI,Rs=2*Fs,Ws=Rs-Hs,zs=Fs/2,qs=Fs/180,Us=180/Fs,Bs=Math.SQRT2,Vs=2,Xs=4;is.interpolateZoom=function(t,e){function n(t){var e=t*y;if(v){var n=ie(g),a=o/(Vs*h)*(n*oe(Bs*e+g)-re(g));return[r+a*u,i+a*c,o*n/ie(Bs*e+g)]}return[r+t*u,i+t*c,o*Math.exp(Bs*e)]}var r=t[0],i=t[1],o=t[2],a=e[0],s=e[1],l=e[2],u=a-r,c=s-i,f=u*u+c*c,h=Math.sqrt(f),d=(l*l-o*o+Xs*f)/(2*o*Vs*h),p=(l*l-o*o-Xs*f)/(2*l*Vs*h),g=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(p*p+1)-p),v=m-g,y=(v||Math.log(l/o))/Bs;n.duration=1e3*y;return n};is.behavior.zoom=function(){function t(t){t.on(A,c).on(Ys+".zoom",h).on("dblclick.zoom",d).on(j,f)}function e(t){return[(t[0]-T.x)/T.k,(t[1]-T.y)/T.k]}function n(t){return[t[0]*T.k+T.x,t[1]*T.k+T.y]}function r(t){T.k=Math.max(M[0],Math.min(M[1],t))}function i(t,e){e=n(e);T.x+=t[0]-e[0];T.y+=t[1]-e[1]}function o(e,n,o,a){e.__chart__={x:T.x,y:T.y,k:T.k};r(Math.pow(2,a));i(g=n,o);e=is.select(e);D>0&&(e=e.transition().duration(D));e.call(t.event)}function a(){x&&x.domain(b.range().map(function(t){return(t-T.x)/T.k}).map(b.invert));C&&C.domain(w.range().map(function(t){return(t-T.y)/T.k}).map(w.invert))}function s(t){L++||t({type:"zoomstart"})}function l(t){a();t({type:"zoom",scale:T.k,translate:[T.x,T.y]})}function u(t){--L||t({type:"zoomend"});g=null}function c(){function t(){c=1;i(is.mouse(r),h);l(a)}function n(){f.on(N,null).on(E,null);d(c&&is.event.target===o);u(a)}var r=this,o=is.event.target,a=I.of(r,arguments),c=0,f=is.select(us).on(N,t).on(E,n),h=e(is.mouse(r)),d=$();qu.call(r);s(a)}function f(){function t(){var t=is.touches(p);d=T.k;t.forEach(function(t){t.identifier in m&&(m[t.identifier]=e(t))});return t}function n(){var e=is.event.target;is.select(e).on(x,a).on(w,h);C.push(e);for(var n=is.event.changedTouches,r=0,i=n.length;i>r;++r)m[n[r].identifier]=null;var s=t(),l=Date.now();if(1===s.length){if(500>l-y){var u=s[0];o(p,u,m[u.identifier],Math.floor(Math.log(T.k)/Math.LN2)+1);S()}y=l}else if(s.length>1){var u=s[0],c=s[1],f=u[0]-c[0],d=u[1]-c[1];v=f*f+d*d}}function a(){var t,e,n,o,a=is.touches(p);qu.call(p);for(var s=0,u=a.length;u>s;++s,o=null){n=a[s];if(o=m[n.identifier]){if(e)break;t=n,e=o}}if(o){var c=(c=n[0]-t[0])*c+(c=n[1]-t[1])*c,f=v&&Math.sqrt(c/v);t=[(t[0]+n[0])/2,(t[1]+n[1])/2];e=[(e[0]+o[0])/2,(e[1]+o[1])/2];r(f*d)}y=null;i(t,e);l(g)}function h(){if(is.event.touches.length){for(var e=is.event.changedTouches,n=0,r=e.length;r>n;++n)delete m[e[n].identifier];for(var i in m)return void t()}is.selectAll(C).on(b,null);k.on(A,c).on(j,f);_();u(g)}var d,p=this,g=I.of(p,arguments),m={},v=0,b=".zoom-"+is.event.changedTouches[0].identifier,x="touchmove"+b,w="touchend"+b,C=[],k=is.select(p),_=$();n();s(g);k.on(A,null).on(j,n)}function h(){var t=I.of(this,arguments);v?clearTimeout(v):(p=e(g=m||is.mouse(this)),qu.call(this),s(t));v=setTimeout(function(){v=null;u(t)},50);S();r(Math.pow(2,.002*Gs())*T.k);i(g,p);l(t)}function d(){var t=is.mouse(this),n=Math.log(T.k)/Math.LN2;o(this,t,e(t),is.event.shiftKey?Math.ceil(n)-1:Math.floor(n)+1)}var p,g,m,v,y,b,x,w,C,T={x:0,y:0,k:1},_=[960,500],M=$s,D=250,L=0,A="mousedown.zoom",N="mousemove.zoom",E="mouseup.zoom",j="touchstart.zoom",I=k(t,"zoomstart","zoom","zoomend");t.event=function(t){t.each(function(){var t=I.of(this,arguments),e=T;if(Wu)is.select(this).transition().each("start.zoom",function(){T=this.__chart__||{x:0,y:0,k:1};s(t)}).tween("zoom:zoom",function(){var n=_[0],r=_[1],i=g?g[0]:n/2,o=g?g[1]:r/2,a=is.interpolateZoom([(i-T.x)/T.k,(o-T.y)/T.k,n/T.k],[(i-e.x)/e.k,(o-e.y)/e.k,n/e.k]);return function(e){var r=a(e),s=n/r[2];this.__chart__=T={x:i-r[0]*s,y:o-r[1]*s,k:s};l(t)}}).each("interrupt.zoom",function(){u(t)}).each("end.zoom",function(){u(t)});else{this.__chart__=T;s(t);l(t);u(t)}})};t.translate=function(e){if(!arguments.length)return[T.x,T.y];T={x:+e[0],y:+e[1],k:T.k};a();return t};t.scale=function(e){if(!arguments.length)return T.k;T={x:T.x,y:T.y,k:+e};a();return t};t.scaleExtent=function(e){if(!arguments.length)return M;M=null==e?$s:[+e[0],+e[1]];return t};t.center=function(e){if(!arguments.length)return m;m=e&&[+e[0],+e[1]];return t};t.size=function(e){if(!arguments.length)return _;_=e&&[+e[0],+e[1]];return t};t.duration=function(e){if(!arguments.length)return D;D=+e;return t};t.x=function(e){if(!arguments.length)return x;x=e;b=e.copy();T={x:0,y:0,k:1};return t};t.y=function(e){if(!arguments.length)return C;C=e;w=e.copy();T={x:0,y:0,k:1};return t};return is.rebind(t,I,"on")};var Gs,$s=[0,1/0],Ys="onwheel"in ss?(Gs=function(){return-is.event.deltaY*(is.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ss?(Gs=function(){return is.event.wheelDelta},"mousewheel"):(Gs=function(){return-is.event.detail},"MozMousePixelScroll");is.color=se;se.prototype.toString=function(){return this.rgb()+""};is.hsl=le;var Js=le.prototype=new se;Js.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);return new le(this.h,this.s,this.l/t)};Js.darker=function(t){t=Math.pow(.7,arguments.length?t:1);return new le(this.h,this.s,t*this.l)};Js.rgb=function(){return ue(this.h,this.s,this.l)};is.hcl=ce;var Ks=ce.prototype=new se;Ks.brighter=function(t){return new ce(this.h,this.c,Math.min(100,this.l+Zs*(arguments.length?t:1)))};Ks.darker=function(t){return new ce(this.h,this.c,Math.max(0,this.l-Zs*(arguments.length?t:1)))};Ks.rgb=function(){return fe(this.h,this.c,this.l).rgb()};is.lab=he;var Zs=18,Qs=.95047,tl=1,el=1.08883,nl=he.prototype=new se;nl.brighter=function(t){return new he(Math.min(100,this.l+Zs*(arguments.length?t:1)),this.a,this.b)};nl.darker=function(t){return new he(Math.max(0,this.l-Zs*(arguments.length?t:1)),this.a,this.b)};nl.rgb=function(){return de(this.l,this.a,this.b)};is.rgb=ye;var rl=ye.prototype=new se;rl.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,n=this.g,r=this.b,i=30;if(!e&&!n&&!r)return new ye(i,i,i);e&&i>e&&(e=i);n&&i>n&&(n=i);r&&i>r&&(r=i);return new ye(Math.min(255,e/t),Math.min(255,n/t),Math.min(255,r/t))};rl.darker=function(t){t=Math.pow(.7,arguments.length?t:1);return new ye(t*this.r,t*this.g,t*this.b)};rl.hsl=function(){return Se(this.r,this.g,this.b)};rl.toString=function(){return"#"+we(this.r)+we(this.g)+we(this.b)};var il=is.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});il.forEach(function(t,e){il.set(t,be(e))});is.functor=Me;is.xhr=Le(De);is.dsv=function(t,e){function n(t,n,o){arguments.length<3&&(o=n,n=null);var a=Ae(t,e,null==n?r:i(n),o);a.row=function(t){return arguments.length?a.response(null==(n=t)?r:i(t)):n};return a}function r(t){return n.parse(t.responseText)}function i(t){return function(e){return n.parse(e.responseText,t)}}function o(e){return e.map(a).join(t)}function a(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);n.parse=function(t,e){var r;return n.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,n){return e(i(t),n)}:i})};n.parseRows=function(t,e){function n(){if(c>=u)return a;if(i)return i=!1,o;var e=c;if(34===t.charCodeAt(e)){for(var n=e;n++<u;)if(34===t.charCodeAt(n)){if(34!==t.charCodeAt(n+1))break;++n}c=n+2;var r=t.charCodeAt(n+1);if(13===r){i=!0;10===t.charCodeAt(n+2)&&++c}else 10===r&&(i=!0);return t.slice(e+1,n).replace(/""/g,'"')}for(;u>c;){var r=t.charCodeAt(c++),s=1;if(10===r)i=!0;else if(13===r){i=!0;10===t.charCodeAt(c)&&(++c,++s)}else if(r!==l)continue;return t.slice(e,c-s)}return t.slice(e)}for(var r,i,o={},a={},s=[],u=t.length,c=0,f=0;(r=n())!==a;){for(var h=[];r!==o&&r!==a;){h.push(r);r=n()}e&&null==(h=e(h,f++))||s.push(h)}return s};n.format=function(e){if(Array.isArray(e[0]))return n.formatRows(e);var r=new v,i=[];e.forEach(function(t){for(var e in t)r.has(e)||i.push(r.add(e))});return[i.map(a).join(t)].concat(e.map(function(e){return i.map(function(t){return a(e[t])}).join(t)})).join("\n")};n.formatRows=function(t){return t.map(o).join("\n")};return n};is.csv=is.dsv(",","text/csv");is.tsv=is.dsv(" ","text/tab-separated-values");var ol,al,sl,ll,ul,cl=us[b(us,"requestAnimationFrame")]||function(t){setTimeout(t,17)};is.timer=function(t,e,n){var r=arguments.length;2>r&&(e=0);3>r&&(n=Date.now());var i=n+e,o={c:t,t:i,f:!1,n:null};al?al.n=o:ol=o;al=o;if(!sl){ll=clearTimeout(ll);sl=1;cl(je)}};is.timer.flush=function(){Ie();Pe()};is.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var fl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Oe);is.formatPrefix=function(t,e){var n=0;if(t){0>t&&(t*=-1);e&&(t=is.round(t,He(t,e)));n=1+Math.floor(1e-12+Math.log(t)/Math.LN10);n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))}return fl[8+n/3]};var hl=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,dl=is.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=is.round(t,He(t,e))).toFixed(Math.max(0,Math.min(20,He(t*(1+1e-15),e))))}}),pl=is.time={},gl=Date;We.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ml.setUTCDate.apply(this._,arguments)},setDay:function(){ml.setUTCDay.apply(this._,arguments)},setFullYear:function(){ml.setUTCFullYear.apply(this._,arguments)},setHours:function(){ml.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ml.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ml.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ml.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ml.setUTCSeconds.apply(this._,arguments)},setTime:function(){ml.setTime.apply(this._,arguments)}};var ml=Date.prototype;pl.year=ze(function(t){t=pl.day(t);t.setMonth(0,1);return t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()});pl.years=pl.year.range;pl.years.utc=pl.year.utc.range;pl.day=ze(function(t){var e=new gl(2e3,0);e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate());return e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1});pl.days=pl.day.range;pl.days.utc=pl.day.utc.range;pl.dayOfYear=function(t){var e=pl.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)};["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var n=pl[t]=ze(function(t){(t=pl.day(t)).setDate(t.getDate()-(t.getDay()+e)%7);return t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var n=pl.year(t).getDay();return Math.floor((pl.dayOfYear(t)+(n+e)%7)/7)-(n!==e)});pl[t+"s"]=n.range;pl[t+"s"].utc=n.utc.range;pl[t+"OfYear"]=function(t){var n=pl.year(t).getDay();return Math.floor((pl.dayOfYear(t)+(n+e)%7)/7)}});pl.week=pl.sunday;pl.weeks=pl.sunday.range;pl.weeks.utc=pl.sunday.utc.range;pl.weekOfYear=pl.sundayOfYear;var vl={"-":"",_:" ",0:"0"},yl=/^\s*\d+/,bl=/^%/; is.locale=function(t){return{numberFormat:Fe(t),timeFormat:Ue(t)}};var xl=is.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});is.format=xl.numberFormat;is.geo={};fn.prototype={s:0,t:0,add:function(t){hn(t,this.t,wl);hn(wl.s,this.s,this);this.s?this.t+=wl.t:this.s=wl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var wl=new fn;is.geo.stream=function(t,e){t&&Cl.hasOwnProperty(t.type)?Cl[t.type](t,e):dn(t,e)};var Cl={Feature:function(t,e){dn(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r<i;)dn(n[r].geometry,e)}},Sl={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates;e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)t=n[r],e.point(t[0],t[1],t[2])},LineString:function(t,e){pn(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)pn(n[r],e,0)},Polygon:function(t,e){gn(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)gn(n[r],e)},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,i=n.length;++r<i;)dn(n[r],e)}};is.geo.area=function(t){Tl=0;is.geo.stream(t,_l);return Tl};var Tl,kl=new fn,_l={sphere:function(){Tl+=4*Fs},point:x,lineStart:x,lineEnd:x,polygonStart:function(){kl.reset();_l.lineStart=mn},polygonEnd:function(){var t=2*kl;Tl+=0>t?4*Fs+t:t;_l.lineStart=_l.lineEnd=_l.point=x}};is.geo.bounds=function(){function t(t,e){b.push(x=[c=t,h=t]);f>e&&(f=e);e>d&&(d=e)}function e(e,n){var r=vn([e*qs,n*qs]);if(v){var i=bn(v,r),o=[i[1],-i[0],0],a=bn(o,i);Cn(a);a=Sn(a);var l=e-p,u=l>0?1:-1,g=a[0]*Us*u,m=ys(l)>180;if(m^(g>u*p&&u*e>g)){var y=a[1]*Us;y>d&&(d=y)}else if(g=(g+360)%360-180,m^(g>u*p&&u*e>g)){var y=-a[1]*Us;f>y&&(f=y)}else{f>n&&(f=n);n>d&&(d=n)}if(m)p>e?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e);else if(h>=c){c>e&&(c=e);e>h&&(h=e)}else e>p?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e)}else t(e,n);v=r,p=e}function n(){w.point=e}function r(){x[0]=c,x[1]=h;w.point=t;v=null}function i(t,n){if(v){var r=t-p;y+=ys(r)>180?r+(r>0?360:-360):r}else g=t,m=n;_l.point(t,n);e(t,n)}function o(){_l.lineStart()}function a(){i(g,m);_l.lineEnd();ys(y)>Hs&&(c=-(h=180));x[0]=c,x[1]=h;v=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}var c,f,h,d,p,g,m,v,y,b,x,w={point:t,lineStart:n,lineEnd:r,polygonStart:function(){w.point=i;w.lineStart=o;w.lineEnd=a;y=0;_l.polygonStart()},polygonEnd:function(){_l.polygonEnd();w.point=t;w.lineStart=n;w.lineEnd=r;0>kl?(c=-(h=180),f=-(d=90)):y>Hs?d=90:-Hs>y&&(f=-90);x[0]=c,x[1]=h}};return function(t){d=h=-(c=f=1/0);b=[];is.geo.stream(t,w);var e=b.length;if(e){b.sort(l);for(var n,r=1,i=b[0],o=[i];e>r;++r){n=b[r];if(u(n[0],i)||u(n[1],i)){s(i[0],n[1])>s(i[0],i[1])&&(i[1]=n[1]);s(n[0],i[1])>s(i[0],i[1])&&(i[0]=n[0])}else o.push(i=n)}for(var a,n,p=-1/0,e=o.length-1,r=0,i=o[e];e>=r;i=n,++r){n=o[r];(a=s(i[1],n[0]))>p&&(p=a,c=n[0],h=i[1])}}b=x=null;return 1/0===c||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[c,f],[h,d]]}}();is.geo.centroid=function(t){Ml=Dl=Ll=Al=Nl=El=jl=Il=Pl=Hl=Ol=0;is.geo.stream(t,Fl);var e=Pl,n=Hl,r=Ol,i=e*e+n*n+r*r;if(Os>i){e=El,n=jl,r=Il;Hs>Dl&&(e=Ll,n=Al,r=Nl);i=e*e+n*n+r*r;if(Os>i)return[0/0,0/0]}return[Math.atan2(n,e)*Us,ne(r/Math.sqrt(i))*Us]};var Ml,Dl,Ll,Al,Nl,El,jl,Il,Pl,Hl,Ol,Fl={sphere:x,point:kn,lineStart:Mn,lineEnd:Dn,polygonStart:function(){Fl.lineStart=Ln},polygonEnd:function(){Fl.lineStart=Mn}},Rl=Pn(Nn,Rn,zn,[-Fs,-Fs/2]),Wl=1e9;is.geo.clipExtent=function(){var t,e,n,r,i,o,a={stream:function(t){i&&(i.valid=!1);i=o(t);i.valid=!0;return i},extent:function(s){if(!arguments.length)return[[t,e],[n,r]];o=Vn(t=+s[0][0],e=+s[0][1],n=+s[1][0],r=+s[1][1]);i&&(i.valid=!1,i=null);return a}};return a.extent([[0,0],[960,500]])};(is.geo.conicEqualArea=function(){return Xn(Gn)}).raw=Gn;is.geo.albers=function(){return is.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};is.geo.albersUsa=function(){function t(t){var o=t[0],a=t[1];e=null;(n(o,a),e)||(r(o,a),e)||i(o,a);return e}var e,n,r,i,o=is.geo.albers(),a=is.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=is.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,n){e=[t,n]}};t.invert=function(t){var e=o.scale(),n=o.translate(),r=(t[0]-n[0])/e,i=(t[1]-n[1])/e;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?a:i>=.166&&.234>i&&r>=-.214&&-.115>r?s:o).invert(t)};t.stream=function(t){var e=o.stream(t),n=a.stream(t),r=s.stream(t);return{point:function(t,i){e.point(t,i);n.point(t,i);r.point(t,i)},sphere:function(){e.sphere();n.sphere();r.sphere()},lineStart:function(){e.lineStart();n.lineStart();r.lineStart()},lineEnd:function(){e.lineEnd();n.lineEnd();r.lineEnd()},polygonStart:function(){e.polygonStart();n.polygonStart();r.polygonStart()},polygonEnd:function(){e.polygonEnd();n.polygonEnd();r.polygonEnd()}}};t.precision=function(e){if(!arguments.length)return o.precision();o.precision(e);a.precision(e);s.precision(e);return t};t.scale=function(e){if(!arguments.length)return o.scale();o.scale(e);a.scale(.35*e);s.scale(e);return t.translate(o.translate())};t.translate=function(e){if(!arguments.length)return o.translate();var u=o.scale(),c=+e[0],f=+e[1];n=o.translate(e).clipExtent([[c-.455*u,f-.238*u],[c+.455*u,f+.238*u]]).stream(l).point;r=a.translate([c-.307*u,f+.201*u]).clipExtent([[c-.425*u+Hs,f+.12*u+Hs],[c-.214*u-Hs,f+.234*u-Hs]]).stream(l).point;i=s.translate([c-.205*u,f+.212*u]).clipExtent([[c-.214*u+Hs,f+.166*u+Hs],[c-.115*u-Hs,f+.234*u-Hs]]).stream(l).point;return t};return t.scale(1070)};var zl,ql,Ul,Bl,Vl,Xl,Gl={point:x,lineStart:x,lineEnd:x,polygonStart:function(){ql=0;Gl.lineStart=$n},polygonEnd:function(){Gl.lineStart=Gl.lineEnd=Gl.point=x;zl+=ys(ql/2)}},$l={point:Yn,lineStart:x,lineEnd:x,polygonStart:x,polygonEnd:x},Yl={point:Zn,lineStart:Qn,lineEnd:tr,polygonStart:function(){Yl.lineStart=er},polygonEnd:function(){Yl.point=Zn;Yl.lineStart=Qn;Yl.lineEnd=tr}};is.geo.path=function(){function t(t){if(t){"function"==typeof s&&o.pointRadius(+s.apply(this,arguments));a&&a.valid||(a=i(o));is.geo.stream(t,a)}return o.result()}function e(){a=null;return t}var n,r,i,o,a,s=4.5;t.area=function(t){zl=0;is.geo.stream(t,i(Gl));return zl};t.centroid=function(t){Ll=Al=Nl=El=jl=Il=Pl=Hl=Ol=0;is.geo.stream(t,i(Yl));return Ol?[Pl/Ol,Hl/Ol]:Il?[El/Il,jl/Il]:Nl?[Ll/Nl,Al/Nl]:[0/0,0/0]};t.bounds=function(t){Vl=Xl=-(Ul=Bl=1/0);is.geo.stream(t,i($l));return[[Ul,Bl],[Vl,Xl]]};t.projection=function(t){if(!arguments.length)return n;i=(n=t)?t.stream||ir(t):De;return e()};t.context=function(t){if(!arguments.length)return r;o=null==(r=t)?new Jn:new nr(t);"function"!=typeof s&&o.pointRadius(s);return e()};t.pointRadius=function(e){if(!arguments.length)return s;s="function"==typeof e?e:(o.pointRadius(+e),+e);return t};return t.projection(is.geo.albersUsa()).context(null)};is.geo.transform=function(t){return{stream:function(e){var n=new or(e);for(var r in t)n[r]=t[r];return n}}};or.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};is.geo.projection=sr;is.geo.projectionMutator=lr;(is.geo.equirectangular=function(){return sr(cr)}).raw=cr.invert=cr;is.geo.rotation=function(t){function e(e){e=t(e[0]*qs,e[1]*qs);return e[0]*=Us,e[1]*=Us,e}t=hr(t[0]%360*qs,t[1]*qs,t.length>2?t[2]*qs:0);e.invert=function(e){e=t.invert(e[0]*qs,e[1]*qs);return e[0]*=Us,e[1]*=Us,e};return e};fr.invert=cr;is.geo.circle=function(){function t(){var t="function"==typeof r?r.apply(this,arguments):r,e=hr(-t[0]*qs,-t[1]*qs,0).invert,i=[];n(null,null,1,{point:function(t,n){i.push(t=e(t,n));t[0]*=Us,t[1]*=Us}});return{type:"Polygon",coordinates:[i]}}var e,n,r=[0,0],i=6;t.origin=function(e){if(!arguments.length)return r;r=e;return t};t.angle=function(r){if(!arguments.length)return e;n=mr((e=+r)*qs,i*qs);return t};t.precision=function(r){if(!arguments.length)return i;n=mr(e*qs,(i=+r)*qs);return t};return t.angle(90)};is.geo.distance=function(t,e){var n,r=(e[0]-t[0])*qs,i=t[1]*qs,o=e[1]*qs,a=Math.sin(r),s=Math.cos(r),l=Math.sin(i),u=Math.cos(i),c=Math.sin(o),f=Math.cos(o);return Math.atan2(Math.sqrt((n=f*a)*n+(n=u*c-l*f*s)*n),l*c+u*f*s)};is.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return is.range(Math.ceil(o/m)*m,i,m).map(h).concat(is.range(Math.ceil(u/v)*v,l,v).map(d)).concat(is.range(Math.ceil(r/p)*p,n,p).filter(function(t){return ys(t%m)>Hs}).map(c)).concat(is.range(Math.ceil(s/g)*g,a,g).filter(function(t){return ys(t%v)>Hs}).map(f))}var n,r,i,o,a,s,l,u,c,f,h,d,p=10,g=p,m=90,v=360,y=2.5;t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})};t.outline=function(){return{type:"Polygon",coordinates:[h(o).concat(d(l).slice(1),h(i).reverse().slice(1),d(u).reverse().slice(1))]}};t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()};t.majorExtent=function(e){if(!arguments.length)return[[o,u],[i,l]];o=+e[0][0],i=+e[1][0];u=+e[0][1],l=+e[1][1];o>i&&(e=o,o=i,i=e);u>l&&(e=u,u=l,l=e);return t.precision(y)};t.minorExtent=function(e){if(!arguments.length)return[[r,s],[n,a]];r=+e[0][0],n=+e[1][0];s=+e[0][1],a=+e[1][1];r>n&&(e=r,r=n,n=e);s>a&&(e=s,s=a,a=e);return t.precision(y)};t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()};t.majorStep=function(e){if(!arguments.length)return[m,v];m=+e[0],v=+e[1];return t};t.minorStep=function(e){if(!arguments.length)return[p,g];p=+e[0],g=+e[1];return t};t.precision=function(e){if(!arguments.length)return y;y=+e;c=yr(s,a,90);f=br(r,n,y);h=yr(u,l,90);d=br(o,i,y);return t};return t.majorExtent([[-180,-90+Hs],[180,90-Hs]]).minorExtent([[-180,-80-Hs],[180,80+Hs]])};is.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||i.apply(this,arguments)]}}var e,n,r=xr,i=wr;t.distance=function(){return is.geo.distance(e||r.apply(this,arguments),n||i.apply(this,arguments))};t.source=function(n){if(!arguments.length)return r;r=n,e="function"==typeof n?null:n;return t};t.target=function(e){if(!arguments.length)return i;i=e,n="function"==typeof e?null:e;return t};t.precision=function(){return arguments.length?t:0};return t};is.geo.interpolate=function(t,e){return Cr(t[0]*qs,t[1]*qs,e[0]*qs,e[1]*qs)};is.geo.length=function(t){Jl=0;is.geo.stream(t,Kl);return Jl};var Jl,Kl={sphere:x,point:x,lineStart:Sr,lineEnd:x,polygonStart:x,polygonEnd:x},Zl=Tr(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(is.geo.azimuthalEqualArea=function(){return sr(Zl)}).raw=Zl;var Ql=Tr(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},De);(is.geo.azimuthalEquidistant=function(){return sr(Ql)}).raw=Ql;(is.geo.conicConformal=function(){return Xn(kr)}).raw=kr;(is.geo.conicEquidistant=function(){return Xn(_r)}).raw=_r;var tu=Tr(function(t){return 1/t},Math.atan);(is.geo.gnomonic=function(){return sr(tu)}).raw=tu;Mr.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-zs]};(is.geo.mercator=function(){return Dr(Mr)}).raw=Mr;var eu=Tr(function(){return 1},Math.asin);(is.geo.orthographic=function(){return sr(eu)}).raw=eu;var nu=Tr(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(is.geo.stereographic=function(){return sr(nu)}).raw=nu;Lr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-zs]};(is.geo.transverseMercator=function(){var t=Dr(Lr),e=t.center,n=t.rotate;t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])};t.rotate=function(t){return t?n([t[0],t[1],t.length>2?t[2]+90:90]):(t=n(),[t[0],t[1],t[2]-90])};return n([0,0,90])}).raw=Lr;is.geom={};is.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Me(n),o=Me(r),a=t.length,s=[],l=[];for(e=0;a>e;e++)s.push([+i.call(this,t[e],e),+o.call(this,t[e],e),e]);s.sort(jr);for(e=0;a>e;e++)l.push([s[e][0],-s[e][1]]);var u=Er(s),c=Er(l),f=c[0]===u[0],h=c[c.length-1]===u[u.length-1],d=[];for(e=u.length-1;e>=0;--e)d.push(t[s[u[e]][2]]);for(e=+f;e<c.length-h;++e)d.push(t[s[c[e]][2]]);return d}var n=Ar,r=Nr;if(arguments.length)return e(t);e.x=function(t){return arguments.length?(n=t,e):n};e.y=function(t){return arguments.length?(r=t,e):r};return e};is.geom.polygon=function(t){Ss(t,ru);return t};var ru=is.geom.polygon.prototype=[];ru.area=function(){for(var t,e=-1,n=this.length,r=this[n-1],i=0;++e<n;){t=r;r=this[e];i+=t[1]*r[0]-t[0]*r[1]}return.5*i};ru.centroid=function(t){var e,n,r=-1,i=this.length,o=0,a=0,s=this[i-1];arguments.length||(t=-1/(6*this.area()));for(;++r<i;){e=s;s=this[r];n=e[0]*s[1]-s[0]*e[1];o+=(e[0]+s[0])*n;a+=(e[1]+s[1])*n}return[o*t,a*t]};ru.clip=function(t){for(var e,n,r,i,o,a,s=Hr(t),l=-1,u=this.length-Hr(this),c=this[u-1];++l<u;){e=t.slice();t.length=0;i=this[l];o=e[(r=e.length-s)-1];n=-1;for(;++n<r;){a=e[n];if(Ir(a,c,i)){Ir(o,c,i)||t.push(Pr(o,a,c,i));t.push(a)}else Ir(o,c,i)&&t.push(Pr(o,a,c,i));o=a}s&&t.push(t[0]);c=i}return t};var iu,ou,au,su,lu,uu=[],cu=[];Br.prototype.prepare=function(){for(var t,e=this.edges,n=e.length;n--;){t=e[n].edge;t.b&&t.a||e.splice(n,1)}e.sort(Xr);return e.length};ni.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}};ri.prototype={insert:function(t,e){var n,r,i;if(t){e.P=t;e.N=t.N;t.N&&(t.N.P=e);t.N=e;if(t.R){t=t.R;for(;t.L;)t=t.L;t.L=e}else t.R=e;n=t}else if(this._){t=si(this._);e.P=null;e.N=t;t.P=t.L=e;n=t}else{e.P=e.N=null;this._=e;n=null}e.L=e.R=null;e.U=n;e.C=!0;t=e;for(;n&&n.C;){r=n.U;if(n===r.L){i=r.R;if(i&&i.C){n.C=i.C=!1;r.C=!0;t=r}else{if(t===n.R){oi(this,n);t=n;n=t.U}n.C=!1;r.C=!0;ai(this,r)}}else{i=r.L;if(i&&i.C){n.C=i.C=!1;r.C=!0;t=r}else{if(t===n.L){ai(this,n);t=n;n=t.U}n.C=!1;r.C=!0;oi(this,r)}}n=t.U}this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P);t.P&&(t.P.N=t.N);t.N=t.P=null;var e,n,r,i=t.U,o=t.L,a=t.R;n=o?a?si(a):o:a;i?i.L===t?i.L=n:i.R=n:this._=n;if(o&&a){r=n.C;n.C=t.C;n.L=o;o.U=n;if(n!==a){i=n.U;n.U=t.U;t=n.R;i.L=t;n.R=a;a.U=n}else{n.U=i;i=n;t=n.R}}else{r=t.C;t=n}t&&(t.U=i);if(!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){e=i.R;if(e.C){e.C=!1;i.C=!0;oi(this,i);e=i.R}if(e.L&&e.L.C||e.R&&e.R.C){if(!e.R||!e.R.C){e.L.C=!1;e.C=!0;ai(this,e);e=i.R}e.C=i.C;i.C=e.R.C=!1;oi(this,i);t=this._;break}}else{e=i.L;if(e.C){e.C=!1;i.C=!0;ai(this,i);e=i.L}if(e.L&&e.L.C||e.R&&e.R.C){if(!e.L||!e.L.C){e.R.C=!1;e.C=!0;oi(this,e);e=i.L}e.C=i.C;i.C=e.L.C=!1;ai(this,i);t=this._;break}}e.C=!0;t=i;i=i.U}while(!t.C);t&&(t.C=!1)}}};is.geom.voronoi=function(t){function e(t){var e=new Array(t.length),r=s[0][0],i=s[0][1],o=s[1][0],a=s[1][1];li(n(t),s).cells.forEach(function(n,s){var l=n.edges,u=n.site,c=e[s]=l.length?l.map(function(t){var e=t.start();return[e.x,e.y]}):u.x>=r&&u.x<=o&&u.y>=i&&u.y<=a?[[r,a],[o,a],[o,i],[r,i]]:[];c.point=t[s]});return e}function n(t){return t.map(function(t,e){return{x:Math.round(o(t,e)/Hs)*Hs,y:Math.round(a(t,e)/Hs)*Hs,i:e}})}var r=Ar,i=Nr,o=r,a=i,s=fu;if(t)return e(t);e.links=function(t){return li(n(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})};e.triangles=function(t){var e=[];li(n(t)).cells.forEach(function(n,r){for(var i,o,a=n.site,s=n.edges.sort(Xr),l=-1,u=s.length,c=s[u-1].edge,f=c.l===a?c.r:c.l;++l<u;){i=c;o=f;c=s[l].edge;f=c.l===a?c.r:c.l;r<o.i&&r<f.i&&ci(a,o,f)<0&&e.push([t[r],t[o.i],t[f.i]])}});return e};e.x=function(t){return arguments.length?(o=Me(r=t),e):r};e.y=function(t){return arguments.length?(a=Me(i=t),e):i};e.clipExtent=function(t){if(!arguments.length)return s===fu?null:s;s=null==t?fu:t;return e};e.size=function(t){return arguments.length?e.clipExtent(t&&[[0,0],t]):s===fu?null:s&&s[1]};return e};var fu=[[-1e6,-1e6],[1e6,1e6]];is.geom.delaunay=function(t){return is.geom.voronoi().triangles(t)};is.geom.quadtree=function(t,e,n,r,i){function o(t){function o(t,e,n,r,i,o,a,s){if(!isNaN(n)&&!isNaN(r))if(t.leaf){var l=t.x,c=t.y;if(null!=l)if(ys(l-n)+ys(c-r)<.01)u(t,e,n,r,i,o,a,s);else{var f=t.point;t.x=t.y=t.point=null;u(t,f,l,c,i,o,a,s);u(t,e,n,r,i,o,a,s)}else t.x=n,t.y=r,t.point=e}else u(t,e,n,r,i,o,a,s)}function u(t,e,n,r,i,a,s,l){var u=.5*(i+s),c=.5*(a+l),f=n>=u,h=r>=c,d=h<<1|f;t.leaf=!1;t=t.nodes[d]||(t.nodes[d]=di());f?i=u:s=u;h?a=c:l=c;o(t,e,n,r,i,a,s,l)}var c,f,h,d,p,g,m,v,y,b=Me(s),x=Me(l);if(null!=e)g=e,m=n,v=r,y=i;else{v=y=-(g=m=1/0);f=[],h=[];p=t.length;if(a)for(d=0;p>d;++d){c=t[d];c.x<g&&(g=c.x);c.y<m&&(m=c.y);c.x>v&&(v=c.x);c.y>y&&(y=c.y);f.push(c.x);h.push(c.y)}else for(d=0;p>d;++d){var w=+b(c=t[d],d),C=+x(c,d);g>w&&(g=w);m>C&&(m=C);w>v&&(v=w);C>y&&(y=C);f.push(w);h.push(C)}}var S=v-g,T=y-m;S>T?y=m+S:v=g+T;var k=di();k.add=function(t){o(k,t,+b(t,++d),+x(t,d),g,m,v,y)};k.visit=function(t){pi(t,k,g,m,v,y)};k.find=function(t){return gi(k,t[0],t[1],g,m,v,y)};d=-1;if(null==e){for(;++d<p;)o(k,t[d],f[d],h[d],g,m,v,y);--d}else t.forEach(k.add);f=h=t=c=null;return k}var a,s=Ar,l=Nr;if(a=arguments.length){s=fi;l=hi;if(3===a){i=n;r=e;n=e=0}return o(t)}o.x=function(t){return arguments.length?(s=t,o):s};o.y=function(t){return arguments.length?(l=t,o):l};o.extent=function(t){if(!arguments.length)return null==e?null:[[e,n],[r,i]];null==t?e=n=r=i=null:(e=+t[0][0],n=+t[0][1],r=+t[1][0],i=+t[1][1]);return o};o.size=function(t){if(!arguments.length)return null==e?null:[r-e,i-n];null==t?e=n=r=i=null:(e=n=0,r=+t[0],i=+t[1]);return o};return o};is.interpolateRgb=mi;is.interpolateObject=vi;is.interpolateNumber=yi;is.interpolateString=bi;var hu=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,du=new RegExp(hu.source,"g");is.interpolate=xi;is.interpolators=[function(t,e){var n=typeof e;return("string"===n?il.has(e)||/^(#|rgb\(|hsl\()/.test(e)?mi:bi:e instanceof se?mi:Array.isArray(e)?wi:"object"===n&&isNaN(e)?vi:yi)(t,e)}];is.interpolateArray=wi;var pu=function(){return De},gu=is.map({linear:pu,poly:Di,quad:function(){return ki},cubic:function(){return _i},sin:function(){return Li},exp:function(){return Ai},circle:function(){return Ni},elastic:Ei,back:ji,bounce:function(){return Ii}}),mu=is.map({"in":De,out:Si,"in-out":Ti,"out-in":function(t){return Ti(Si(t))}});is.ease=function(t){var e=t.indexOf("-"),n=e>=0?t.slice(0,e):t,r=e>=0?t.slice(e+1):"in";n=gu.get(n)||pu;r=mu.get(r)||De;return Ci(r(n.apply(null,os.call(arguments,1))))};is.interpolateHcl=Pi;is.interpolateHsl=Hi;is.interpolateLab=Oi;is.interpolateRound=Fi;is.transform=function(t){var e=ss.createElementNS(is.ns.prefix.svg,"g");return(is.transform=function(t){if(null!=t){e.setAttribute("transform",t);var n=e.transform.baseVal.consolidate()}return new Ri(n?n.matrix:vu)})(t)};Ri.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var vu={a:1,b:0,c:0,d:1,e:0,f:0};is.interpolateTransform=Ui;is.layout={};is.layout.bundle=function(){return function(t){for(var e=[],n=-1,r=t.length;++n<r;)e.push(Xi(t[n]));return e}};is.layout.chord=function(){function t(){var t,u,f,h,d,p={},g=[],m=is.range(o),v=[];n=[];r=[];t=0,h=-1;for(;++h<o;){u=0,d=-1;for(;++d<o;)u+=i[h][d];g.push(u);v.push(is.range(o));t+=u}a&&m.sort(function(t,e){return a(g[t],g[e])});s&&v.forEach(function(t,e){t.sort(function(t,n){return s(i[e][t],i[e][n])})});t=(Rs-c*o)/t;u=0,h=-1;for(;++h<o;){f=u,d=-1;for(;++d<o;){var y=m[h],b=v[y][d],x=i[y][b],w=u,C=u+=x*t;p[y+"-"+b]={index:y,subindex:b,startAngle:w,endAngle:C,value:x}}r[y]={index:y,startAngle:f,endAngle:u,value:(u-f)/t};u+=c}h=-1;for(;++h<o;){d=h-1;for(;++d<o;){var S=p[h+"-"+d],T=p[d+"-"+h];(S.value||T.value)&&n.push(S.value<T.value?{source:T,target:S}:{source:S,target:T})}}l&&e()}function e(){n.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}var n,r,i,o,a,s,l,u={},c=0;u.matrix=function(t){if(!arguments.length)return i;o=(i=t)&&i.length;n=r=null;return u};u.padding=function(t){if(!arguments.length)return c;c=t;n=r=null;return u};u.sortGroups=function(t){if(!arguments.length)return a;a=t;n=r=null;return u};u.sortSubgroups=function(t){if(!arguments.length)return s;s=t;n=null;return u};u.sortChords=function(t){if(!arguments.length)return l;l=t;n&&e();return u};u.chords=function(){n||t();return n};u.groups=function(){r||t();return r};return u};is.layout.force=function(){function t(t){return function(e,n,r,i){if(e.point!==t){var o=e.cx-t.x,a=e.cy-t.y,s=i-n,l=o*o+a*a;if(l>s*s/m){if(p>l){var u=e.charge/l;t.px-=o*u;t.py-=a*u}return!0}if(e.point&&l&&p>l){var u=e.pointCharge/l;t.px-=o*u;t.py-=a*u}}return!e.charge}}function e(t){t.px=is.event.x,t.py=is.event.y;s.resume()}var n,r,i,o,a,s={},l=is.dispatch("start","tick","end"),u=[1,1],c=.9,f=yu,h=bu,d=-30,p=xu,g=.1,m=.64,v=[],y=[];s.tick=function(){if((r*=.99)<.005){l.end({type:"end",alpha:r=0});return!0}var e,n,s,f,h,p,m,b,x,w=v.length,C=y.length;for(n=0;C>n;++n){s=y[n];f=s.source;h=s.target;b=h.x-f.x;x=h.y-f.y;if(p=b*b+x*x){p=r*o[n]*((p=Math.sqrt(p))-i[n])/p;b*=p;x*=p;h.x-=b*(m=f.weight/(h.weight+f.weight));h.y-=x*m;f.x+=b*(m=1-m);f.y+=x*m}}if(m=r*g){b=u[0]/2;x=u[1]/2;n=-1;if(m)for(;++n<w;){s=v[n];s.x+=(b-s.x)*m;s.y+=(x-s.y)*m}}if(d){Qi(e=is.geom.quadtree(v),r,a);n=-1;for(;++n<w;)(s=v[n]).fixed||e.visit(t(s))}n=-1;for(;++n<w;){s=v[n];if(s.fixed){s.x=s.px;s.y=s.py}else{s.x-=(s.px-(s.px=s.x))*c;s.y-=(s.py-(s.py=s.y))*c}}l.tick({type:"tick",alpha:r})};s.nodes=function(t){if(!arguments.length)return v;v=t;return s};s.links=function(t){if(!arguments.length)return y;y=t;return s};s.size=function(t){if(!arguments.length)return u;u=t;return s};s.linkDistance=function(t){if(!arguments.length)return f;f="function"==typeof t?t:+t;return s};s.distance=s.linkDistance;s.linkStrength=function(t){if(!arguments.length)return h;h="function"==typeof t?t:+t;return s};s.friction=function(t){if(!arguments.length)return c;c=+t;return s};s.charge=function(t){if(!arguments.length)return d;d="function"==typeof t?t:+t;return s};s.chargeDistance=function(t){if(!arguments.length)return Math.sqrt(p);p=t*t;return s};s.gravity=function(t){if(!arguments.length)return g;g=+t;return s};s.theta=function(t){if(!arguments.length)return Math.sqrt(m);m=t*t;return s};s.alpha=function(t){if(!arguments.length)return r;t=+t;if(r)r=t>0?t:0;else if(t>0){l.start({type:"start",alpha:r=t});is.timer(s.tick)}return s};s.start=function(){function t(t,r){if(!n){n=new Array(l);for(s=0;l>s;++s)n[s]=[];for(s=0;u>s;++s){var i=y[s];n[i.source.index].push(i.target);n[i.target.index].push(i.source)}}for(var o,a=n[e],s=-1,u=a.length;++s<u;)if(!isNaN(o=a[s][t]))return o;return Math.random()*r}var e,n,r,l=v.length,c=y.length,p=u[0],g=u[1];for(e=0;l>e;++e){(r=v[e]).index=e;r.weight=0}for(e=0;c>e;++e){r=y[e];"number"==typeof r.source&&(r.source=v[r.source]);"number"==typeof r.target&&(r.target=v[r.target]);++r.source.weight;++r.target.weight}for(e=0;l>e;++e){r=v[e];isNaN(r.x)&&(r.x=t("x",p));isNaN(r.y)&&(r.y=t("y",g));isNaN(r.px)&&(r.px=r.x);isNaN(r.py)&&(r.py=r.y)}i=[];if("function"==typeof f)for(e=0;c>e;++e)i[e]=+f.call(this,y[e],e);else for(e=0;c>e;++e)i[e]=f;o=[];if("function"==typeof h)for(e=0;c>e;++e)o[e]=+h.call(this,y[e],e);else for(e=0;c>e;++e)o[e]=h;a=[];if("function"==typeof d)for(e=0;l>e;++e)a[e]=+d.call(this,v[e],e);else for(e=0;l>e;++e)a[e]=d;return s.resume()};s.resume=function(){return s.alpha(.1)};s.stop=function(){return s.alpha(0)};s.drag=function(){n||(n=is.behavior.drag().origin(De).on("dragstart.force",Yi).on("drag.force",e).on("dragend.force",Ji));if(!arguments.length)return n;this.on("mouseover.force",Ki).on("mouseout.force",Zi).call(n);return void 0};return is.rebind(s,l,"on")};var yu=20,bu=1,xu=1/0;is.layout.hierarchy=function(){function t(i){var o,a=[i],s=[];i.depth=0;for(;null!=(o=a.pop());){s.push(o);if((u=n.call(t,o,o.depth))&&(l=u.length)){for(var l,u,c;--l>=0;){a.push(c=u[l]);c.parent=o;c.depth=o.depth+1}r&&(o.value=0);o.children=u}else{r&&(o.value=+r.call(t,o,o.depth)||0);delete o.children}}no(i,function(t){var n,i;e&&(n=t.children)&&n.sort(e);r&&(i=t.parent)&&(i.value+=t.value)});return s}var e=oo,n=ro,r=io;t.sort=function(n){if(!arguments.length)return e;e=n;return t};t.children=function(e){if(!arguments.length)return n;n=e;return t};t.value=function(e){if(!arguments.length)return r;r=e;return t};t.revalue=function(e){if(r){eo(e,function(t){t.children&&(t.value=0)});no(e,function(e){var n;e.children||(e.value=+r.call(t,e,e.depth)||0);(n=e.parent)&&(n.value+=e.value)})}return e};return t};is.layout.partition=function(){function t(e,n,r,i){var o=e.children;e.x=n;e.y=e.depth*i;e.dx=r;e.dy=i;if(o&&(a=o.length)){var a,s,l,u=-1;r=e.value?r/e.value:0;for(;++u<a;){t(s=o[u],n,l=s.value*r,i);n+=l}}}function e(t){var n=t.children,r=0;if(n&&(i=n.length))for(var i,o=-1;++o<i;)r=Math.max(r,e(n[o]));return 1+r}function n(n,o){var a=r.call(this,n,o);t(a[0],0,i[0],i[1]/e(a[0]));return a}var r=is.layout.hierarchy(),i=[1,1];n.size=function(t){if(!arguments.length)return i;i=t;return n};return to(n,r)};is.layout.pie=function(){function t(a){var s,l=a.length,u=a.map(function(n,r){return+e.call(t,n,r)}),c=+("function"==typeof r?r.apply(this,arguments):r),f=("function"==typeof i?i.apply(this,arguments):i)-c,h=Math.min(Math.abs(f)/l,+("function"==typeof o?o.apply(this,arguments):o)),d=h*(0>f?-1:1),p=(f-l*d)/is.sum(u),g=is.range(l),m=[];null!=n&&g.sort(n===wu?function(t,e){return u[e]-u[t]}:function(t,e){return n(a[t],a[e])});g.forEach(function(t){m[t]={data:a[t],value:s=u[t],startAngle:c,endAngle:c+=s*p+d,padAngle:h}});return m}var e=Number,n=wu,r=0,i=Rs,o=0;t.value=function(n){if(!arguments.length)return e;e=n;return t};t.sort=function(e){if(!arguments.length)return n;n=e;return t};t.startAngle=function(e){if(!arguments.length)return r;r=e;return t};t.endAngle=function(e){if(!arguments.length)return i;i=e;return t};t.padAngle=function(e){if(!arguments.length)return o;o=e;return t};return t};var wu={};is.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var u=s.map(function(n,r){return e.call(t,n,r)}),c=u.map(function(e){return e.map(function(e,n){return[o.call(t,e,n),a.call(t,e,n)]})}),f=n.call(t,c,l);u=is.permute(u,f);c=is.permute(c,f);var h,d,p,g,m=r.call(t,c,l),v=u[0].length;for(p=0;v>p;++p){i.call(t,u[0][p],g=m[p],c[0][p][1]);for(d=1;h>d;++d)i.call(t,u[d][p],g+=c[d-1][p][1],c[d][p][1])}return s}var e=De,n=co,r=fo,i=uo,o=so,a=lo;t.values=function(n){if(!arguments.length)return e;e=n;return t};t.order=function(e){if(!arguments.length)return n;n="function"==typeof e?e:Cu.get(e)||co;return t};t.offset=function(e){if(!arguments.length)return r;r="function"==typeof e?e:Su.get(e)||fo;return t};t.x=function(e){if(!arguments.length)return o;o=e;return t};t.y=function(e){if(!arguments.length)return a;a=e;return t};t.out=function(e){if(!arguments.length)return i;i=e;return t};return t};var Cu=is.map({"inside-out":function(t){var e,n,r=t.length,i=t.map(ho),o=t.map(po),a=is.range(r).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,u=[],c=[];for(e=0;r>e;++e){n=a[e];if(l>s){s+=o[n];u.push(n)}else{l+=o[n];c.push(n)}}return c.reverse().concat(u)},reverse:function(t){return is.range(t.length).reverse()},"default":co}),Su=is.map({silhouette:function(t){var e,n,r,i=t.length,o=t[0].length,a=[],s=0,l=[];for(n=0;o>n;++n){for(e=0,r=0;i>e;e++)r+=t[e][n][1];r>s&&(s=r);a.push(r)}for(n=0;o>n;++n)l[n]=(s-a[n])/2;return l},wiggle:function(t){var e,n,r,i,o,a,s,l,u,c=t.length,f=t[0],h=f.length,d=[];d[0]=l=u=0;for(n=1;h>n;++n){for(e=0,i=0;c>e;++e)i+=t[e][n][1];for(e=0,o=0,s=f[n][0]-f[n-1][0];c>e;++e){for(r=0,a=(t[e][n][1]-t[e][n-1][1])/(2*s);e>r;++r)a+=(t[r][n][1]-t[r][n-1][1])/s;o+=a*t[e][n][1]}d[n]=l-=i?o/i*s:0;u>l&&(u=l)}for(n=0;h>n;++n)d[n]-=u;return d},expand:function(t){var e,n,r,i=t.length,o=t[0].length,a=1/i,s=[];for(n=0;o>n;++n){for(e=0,r=0;i>e;e++)r+=t[e][n][1];if(r)for(e=0;i>e;e++)t[e][n][1]/=r;else for(e=0;i>e;e++)t[e][n][1]=a}for(n=0;o>n;++n)s[n]=0;return s},zero:fo});is.layout.histogram=function(){function t(t,o){for(var a,s,l=[],u=t.map(n,this),c=r.call(this,u,o),f=i.call(this,c,u,o),o=-1,h=u.length,d=f.length-1,p=e?1:1/h;++o<d;){a=l[o]=[];a.dx=f[o+1]-(a.x=f[o]);a.y=0}if(d>0){o=-1;for(;++o<h;){s=u[o];if(s>=c[0]&&s<=c[1]){a=l[is.bisect(f,s,1,d)-1];a.y+=p;a.push(t[o])}}}return l}var e=!0,n=Number,r=yo,i=mo;t.value=function(e){if(!arguments.length)return n;n=e;return t};t.range=function(e){if(!arguments.length)return r;r=Me(e);return t};t.bins=function(e){if(!arguments.length)return i;i="number"==typeof e?function(t){return vo(t,e)}:Me(e);return t};t.frequency=function(n){if(!arguments.length)return e;e=!!n;return t};return t};is.layout.pack=function(){function t(t,o){var a=n.call(this,t,o),s=a[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};s.x=s.y=0;no(s,function(t){t.r=+c(t.value)});no(s,So);if(r){var f=r*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;no(s,function(t){t.r+=f});no(s,So);no(s,function(t){t.r-=f})}_o(s,l/2,u/2,e?1:1/Math.max(2*s.r/l,2*s.r/u));return a}var e,n=is.layout.hierarchy().sort(bo),r=0,i=[1,1];t.size=function(e){if(!arguments.length)return i;i=e;return t};t.radius=function(n){if(!arguments.length)return e;e=null==n||"function"==typeof n?n:+n;return t};t.padding=function(e){if(!arguments.length)return r;r=+e;return t};return to(t,n)};is.layout.tree=function(){function t(t,i){var c=a.call(this,t,i),f=c[0],h=e(f);no(h,n),h.parent.m=-h.z;eo(h,r);if(u)eo(f,o);else{var d=f,p=f,g=f;eo(f,function(t){t.x<d.x&&(d=t);t.x>p.x&&(p=t);t.depth>g.depth&&(g=t)});var m=s(d,p)/2-d.x,v=l[0]/(p.x+s(p,d)/2+m),y=l[1]/(g.depth||1);eo(f,function(t){t.x=(t.x+m)*v;t.y=t.depth*y})}return c}function e(t){for(var e,n={A:null,children:[t]},r=[n];null!=(e=r.pop());)for(var i,o=e.children,a=0,s=o.length;s>a;++a)r.push((o[a]=i={_:o[a],parent:e,children:(i=o[a].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:a}).a=i);return n.children[0]}function n(t){var e=t.children,n=t.parent.children,r=t.i?n[t.i-1]:null;if(e.length){Eo(t);var o=(e[0].z+e[e.length-1].z)/2;if(r){t.z=r.z+s(t._,r._);t.m=t.z-o}else t.z=o}else r&&(t.z=r.z+s(t._,r._));t.parent.A=i(t,r,t.parent.A||n[0])}function r(t){t._.x=t.z+t.parent.m;t.m+=t.parent.m}function i(t,e,n){if(e){for(var r,i=t,o=t,a=e,l=i.parent.children[0],u=i.m,c=o.m,f=a.m,h=l.m;a=Ao(a),i=Lo(i),a&&i;){l=Lo(l);o=Ao(o);o.a=t;r=a.z+f-i.z-u+s(a._,i._);if(r>0){No(jo(a,t,n),t,r);u+=r;c+=r}f+=a.m;u+=i.m;h+=l.m;c+=o.m}if(a&&!Ao(o)){o.t=a;o.m+=f-c}if(i&&!Lo(l)){l.t=i;l.m+=u-h;n=t}}return n}function o(t){t.x*=l[0];t.y=t.depth*l[1]}var a=is.layout.hierarchy().sort(null).value(null),s=Do,l=[1,1],u=null;t.separation=function(e){if(!arguments.length)return s;s=e;return t};t.size=function(e){if(!arguments.length)return u?null:l;u=null==(l=e)?o:null;return t};t.nodeSize=function(e){if(!arguments.length)return u?l:null;u=null==(l=e)?null:o;return t};return to(t,a)};is.layout.cluster=function(){function t(t,o){var a,s=e.call(this,t,o),l=s[0],u=0;no(l,function(t){var e=t.children;if(e&&e.length){t.x=Po(e);t.y=Io(e)}else{t.x=a?u+=n(t,a):0;t.y=0;a=t}});var c=Ho(l),f=Oo(l),h=c.x-n(c,f)/2,d=f.x+n(f,c)/2;no(l,i?function(t){t.x=(t.x-l.x)*r[0];t.y=(l.y-t.y)*r[1]}:function(t){t.x=(t.x-h)/(d-h)*r[0];t.y=(1-(l.y?t.y/l.y:1))*r[1]});return s}var e=is.layout.hierarchy().sort(null).value(null),n=Do,r=[1,1],i=!1;t.separation=function(e){if(!arguments.length)return n;n=e;return t};t.size=function(e){if(!arguments.length)return i?null:r;i=null==(r=e);return t};t.nodeSize=function(e){if(!arguments.length)return i?r:null;i=null!=(r=e);return t};return to(t,e)};is.layout.treemap=function(){function t(t,e){for(var n,r,i=-1,o=t.length;++i<o;){r=(n=t[i]).value*(0>e?0:e); n.area=isNaN(r)||0>=r?0:r}}function e(n){var o=n.children;if(o&&o.length){var a,s,l,u=f(n),c=[],h=o.slice(),p=1/0,g="slice"===d?u.dx:"dice"===d?u.dy:"slice-dice"===d?1&n.depth?u.dy:u.dx:Math.min(u.dx,u.dy);t(h,u.dx*u.dy/n.value);c.area=0;for(;(l=h.length)>0;){c.push(a=h[l-1]);c.area+=a.area;if("squarify"!==d||(s=r(c,g))<=p){h.pop();p=s}else{c.area-=c.pop().area;i(c,g,u,!1);g=Math.min(u.dx,u.dy);c.length=c.area=0;p=1/0}}if(c.length){i(c,g,u,!0);c.length=c.area=0}o.forEach(e)}}function n(e){var r=e.children;if(r&&r.length){var o,a=f(e),s=r.slice(),l=[];t(s,a.dx*a.dy/e.value);l.area=0;for(;o=s.pop();){l.push(o);l.area+=o.area;if(null!=o.z){i(l,o.z?a.dx:a.dy,a,!s.length);l.length=l.area=0}}r.forEach(n)}}function r(t,e){for(var n,r=t.area,i=0,o=1/0,a=-1,s=t.length;++a<s;)if(n=t[a].area){o>n&&(o=n);n>i&&(i=n)}r*=r;e*=e;return r?Math.max(e*i*p/r,r/(e*o*p)):1/0}function i(t,e,n,r){var i,o=-1,a=t.length,s=n.x,u=n.y,c=e?l(t.area/e):0;if(e==n.dx){(r||c>n.dy)&&(c=n.dy);for(;++o<a;){i=t[o];i.x=s;i.y=u;i.dy=c;s+=i.dx=Math.min(n.x+n.dx-s,c?l(i.area/c):0)}i.z=!0;i.dx+=n.x+n.dx-s;n.y+=c;n.dy-=c}else{(r||c>n.dx)&&(c=n.dx);for(;++o<a;){i=t[o];i.x=s;i.y=u;i.dx=c;u+=i.dy=Math.min(n.y+n.dy-u,c?l(i.area/c):0)}i.z=!1;i.dy+=n.y+n.dy-u;n.x+=c;n.dx-=c}}function o(r){var i=a||s(r),o=i[0];o.x=0;o.y=0;o.dx=u[0];o.dy=u[1];a&&s.revalue(o);t([o],o.dx*o.dy/o.value);(a?n:e)(o);h&&(a=i);return i}var a,s=is.layout.hierarchy(),l=Math.round,u=[1,1],c=null,f=Fo,h=!1,d="squarify",p=.5*(1+Math.sqrt(5));o.size=function(t){if(!arguments.length)return u;u=t;return o};o.padding=function(t){function e(e){var n=t.call(o,e,e.depth);return null==n?Fo(e):Ro(e,"number"==typeof n?[n,n,n,n]:n)}function n(e){return Ro(e,t)}if(!arguments.length)return c;var r;f=null==(c=t)?Fo:"function"==(r=typeof t)?e:"number"===r?(t=[t,t,t,t],n):n;return o};o.round=function(t){if(!arguments.length)return l!=Number;l=t?Math.round:Number;return o};o.sticky=function(t){if(!arguments.length)return h;h=t;a=null;return o};o.ratio=function(t){if(!arguments.length)return p;p=t;return o};o.mode=function(t){if(!arguments.length)return d;d=t+"";return o};return to(o,s)};is.random={normal:function(t,e){var n=arguments.length;2>n&&(e=1);1>n&&(t=0);return function(){var n,r,i;do{n=2*Math.random()-1;r=2*Math.random()-1;i=n*n+r*r}while(!i||i>1);return t+e*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=is.random.normal.apply(is,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=is.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,n=0;t>n;n++)e+=Math.random();return e}}};is.scale={};var Tu={floor:De,ceil:De};is.scale.linear=function(){return Xo([0,1],[0,1],xi,!1)};var ku={s:1,g:1,p:1,r:1,e:1};is.scale.log=function(){return ta(is.scale.linear().domain([0,1]),10,!0,[1,10])};var _u=is.format(".0e"),Mu={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};is.scale.pow=function(){return ea(is.scale.linear(),1,[0,1])};is.scale.sqrt=function(){return is.scale.pow().exponent(.5)};is.scale.ordinal=function(){return ra([],{t:"range",a:[[]]})};is.scale.category10=function(){return is.scale.ordinal().range(Du)};is.scale.category20=function(){return is.scale.ordinal().range(Lu)};is.scale.category20b=function(){return is.scale.ordinal().range(Au)};is.scale.category20c=function(){return is.scale.ordinal().range(Nu)};var Du=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xe),Lu=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xe),Au=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xe),Nu=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xe);is.scale.quantile=function(){return ia([],[])};is.scale.quantize=function(){return oa(0,1,[0,1])};is.scale.threshold=function(){return aa([.5],[0,1])};is.scale.identity=function(){return sa([0,1])};is.svg={};is.svg.arc=function(){function t(){var t=Math.max(0,+n.apply(this,arguments)),u=Math.max(0,+r.apply(this,arguments)),c=a.apply(this,arguments)-zs,f=s.apply(this,arguments)-zs,h=Math.abs(f-c),d=c>f?0:1;t>u&&(p=u,u=t,t=p);if(h>=Ws)return e(u,d)+(t?e(t,1-d):"")+"Z";var p,g,m,v,y,b,x,w,C,S,T,k,_=0,M=0,D=[];if(v=(+l.apply(this,arguments)||0)/2){m=o===Eu?Math.sqrt(t*t+u*u):+o.apply(this,arguments);d||(M*=-1);u&&(M=ne(m/u*Math.sin(v)));t&&(_=ne(m/t*Math.sin(v)))}if(u){y=u*Math.cos(c+M);b=u*Math.sin(c+M);x=u*Math.cos(f-M);w=u*Math.sin(f-M);var L=Math.abs(f-c-2*M)<=Fs?0:1;if(M&&pa(y,b,x,w)===d^L){var A=(c+f)/2;y=u*Math.cos(A);b=u*Math.sin(A);x=w=null}}else y=b=0;if(t){C=t*Math.cos(f-_);S=t*Math.sin(f-_);T=t*Math.cos(c+_);k=t*Math.sin(c+_);var N=Math.abs(c-f+2*_)<=Fs?0:1;if(_&&pa(C,S,T,k)===1-d^N){var E=(c+f)/2;C=t*Math.cos(E);S=t*Math.sin(E);T=k=null}}else C=S=0;if((p=Math.min(Math.abs(u-t)/2,+i.apply(this,arguments)))>.001){g=u>t^d?0:1;var j=null==T?[C,S]:null==x?[y,b]:Pr([y,b],[T,k],[x,w],[C,S]),I=y-j[0],P=b-j[1],H=x-j[0],O=w-j[1],F=1/Math.sin(Math.acos((I*H+P*O)/(Math.sqrt(I*I+P*P)*Math.sqrt(H*H+O*O)))/2),R=Math.sqrt(j[0]*j[0]+j[1]*j[1]);if(null!=x){var W=Math.min(p,(u-R)/(F+1)),z=ga(null==T?[C,S]:[T,k],[y,b],u,W,d),q=ga([x,w],[C,S],u,W,d);p===W?D.push("M",z[0],"A",W,",",W," 0 0,",g," ",z[1],"A",u,",",u," 0 ",1-d^pa(z[1][0],z[1][1],q[1][0],q[1][1]),",",d," ",q[1],"A",W,",",W," 0 0,",g," ",q[0]):D.push("M",z[0],"A",W,",",W," 0 1,",g," ",q[0])}else D.push("M",y,",",b);if(null!=T){var U=Math.min(p,(t-R)/(F-1)),B=ga([y,b],[T,k],t,-U,d),V=ga([C,S],null==x?[y,b]:[x,w],t,-U,d);p===U?D.push("L",V[0],"A",U,",",U," 0 0,",g," ",V[1],"A",t,",",t," 0 ",d^pa(V[1][0],V[1][1],B[1][0],B[1][1]),",",1-d," ",B[1],"A",U,",",U," 0 0,",g," ",B[0]):D.push("L",V[0],"A",U,",",U," 0 0,",g," ",B[0])}else D.push("L",C,",",S)}else{D.push("M",y,",",b);null!=x&&D.push("A",u,",",u," 0 ",L,",",d," ",x,",",w);D.push("L",C,",",S);null!=T&&D.push("A",t,",",t," 0 ",N,",",1-d," ",T,",",k)}D.push("Z");return D.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var n=ua,r=ca,i=la,o=Eu,a=fa,s=ha,l=da;t.innerRadius=function(e){if(!arguments.length)return n;n=Me(e);return t};t.outerRadius=function(e){if(!arguments.length)return r;r=Me(e);return t};t.cornerRadius=function(e){if(!arguments.length)return i;i=Me(e);return t};t.padRadius=function(e){if(!arguments.length)return o;o=e==Eu?Eu:Me(e);return t};t.startAngle=function(e){if(!arguments.length)return a;a=Me(e);return t};t.endAngle=function(e){if(!arguments.length)return s;s=Me(e);return t};t.padAngle=function(e){if(!arguments.length)return l;l=Me(e);return t};t.centroid=function(){var t=(+n.apply(this,arguments)+ +r.apply(this,arguments))/2,e=(+a.apply(this,arguments)+ +s.apply(this,arguments))/2-zs;return[Math.cos(e)*t,Math.sin(e)*t]};return t};var Eu="auto";is.svg.line=function(){return ma(De)};var ju=is.map({linear:va,"linear-closed":ya,step:ba,"step-before":xa,"step-after":wa,basis:Ma,"basis-open":Da,"basis-closed":La,bundle:Aa,cardinal:Ta,"cardinal-open":Ca,"cardinal-closed":Sa,monotone:Ha});ju.forEach(function(t,e){e.key=t;e.closed=/-closed$/.test(t)});var Iu=[0,2/3,1/3,0],Pu=[0,1/3,2/3,0],Hu=[0,1/6,2/3,1/6];is.svg.line.radial=function(){var t=ma(Oa);t.radius=t.x,delete t.x;t.angle=t.y,delete t.y;return t};xa.reverse=wa;wa.reverse=xa;is.svg.area=function(){return Fa(De)};is.svg.area.radial=function(){var t=Fa(Oa);t.radius=t.x,delete t.x;t.innerRadius=t.x0,delete t.x0;t.outerRadius=t.x1,delete t.x1;t.angle=t.y,delete t.y;t.startAngle=t.y0,delete t.y0;t.endAngle=t.y1,delete t.y1;return t};is.svg.chord=function(){function t(t,s){var l=e(this,o,t,s),u=e(this,a,t,s);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(n(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+r(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function e(t,e,n,r){var i=e.call(t,n,r),o=s.call(t,i,r),a=l.call(t,i,r)-zs,c=u.call(t,i,r)-zs;return{r:o,a0:a,a1:c,p0:[o*Math.cos(a),o*Math.sin(a)],p1:[o*Math.cos(c),o*Math.sin(c)]}}function n(t,e){return t.a0==e.a0&&t.a1==e.a1}function r(t,e,n){return"A"+t+","+t+" 0 "+ +(n>Fs)+",1 "+e}function i(t,e,n,r){return"Q 0,0 "+r}var o=xr,a=wr,s=Ra,l=fa,u=ha;t.radius=function(e){if(!arguments.length)return s;s=Me(e);return t};t.source=function(e){if(!arguments.length)return o;o=Me(e);return t};t.target=function(e){if(!arguments.length)return a;a=Me(e);return t};t.startAngle=function(e){if(!arguments.length)return l;l=Me(e);return t};t.endAngle=function(e){if(!arguments.length)return u;u=Me(e);return t};return t};is.svg.diagonal=function(){function t(t,i){var o=e.call(this,t,i),a=n.call(this,t,i),s=(o.y+a.y)/2,l=[o,{x:o.x,y:s},{x:a.x,y:s},a];l=l.map(r);return"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,n=wr,r=Wa;t.source=function(n){if(!arguments.length)return e;e=Me(n);return t};t.target=function(e){if(!arguments.length)return n;n=Me(e);return t};t.projection=function(e){if(!arguments.length)return r;r=e;return t};return t};is.svg.diagonal.radial=function(){var t=is.svg.diagonal(),e=Wa,n=t.projection;t.projection=function(t){return arguments.length?n(za(e=t)):e};return t};is.svg.symbol=function(){function t(t,r){return(Ou.get(e.call(this,t,r))||Ba)(n.call(this,t,r))}var e=Ua,n=qa;t.type=function(n){if(!arguments.length)return e;e=Me(n);return t};t.size=function(e){if(!arguments.length)return n;n=Me(e);return t};return t};var Ou=is.map({circle:Ba,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Ru)),n=e*Ru;return"M0,"+-e+"L"+n+",0 0,"+e+" "+-n+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Fu),n=e*Fu/2;return"M0,"+n+"L"+e+","+-n+" "+-e+","+-n+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Fu),n=e*Fu/2;return"M0,"+-n+"L"+e+","+n+" "+-e+","+n+"Z"}});is.svg.symbolTypes=Ou.keys();var Fu=Math.sqrt(3),Ru=Math.tan(30*qs);Ds.transition=function(t){for(var e,n,r=Wu||++Bu,i=Ya(t),o=[],a=zu||{time:Date.now(),ease:Mi,delay:0,duration:250},s=-1,l=this.length;++s<l;){o.push(e=[]);for(var u=this[s],c=-1,f=u.length;++c<f;){(n=u[c])&&Ja(n,c,i,r,a);e.push(n)}}return Xa(o,i,r)};Ds.interrupt=function(t){return this.each(null==t?qu:Va(Ya(t)))};var Wu,zu,qu=Va(Ya()),Uu=[],Bu=0;Uu.call=Ds.call;Uu.empty=Ds.empty;Uu.node=Ds.node;Uu.size=Ds.size;is.transition=function(t,e){return t&&t.transition?Wu?t.transition(e):t:Ns.transition(t)};is.transition.prototype=Uu;Uu.select=function(t){var e,n,r,i=this.id,o=this.namespace,a=[];t=M(t);for(var s=-1,l=this.length;++s<l;){a.push(e=[]);for(var u=this[s],c=-1,f=u.length;++c<f;)if((r=u[c])&&(n=t.call(r,r.__data__,c,s))){"__data__"in r&&(n.__data__=r.__data__);Ja(n,c,o,i,r[o][i]);e.push(n)}else e.push(null)}return Xa(a,o,i)};Uu.selectAll=function(t){var e,n,r,i,o,a=this.id,s=this.namespace,l=[];t=D(t);for(var u=-1,c=this.length;++u<c;)for(var f=this[u],h=-1,d=f.length;++h<d;)if(r=f[h]){o=r[s][a];n=t.call(r,r.__data__,h,u);l.push(e=[]);for(var p=-1,g=n.length;++p<g;){(i=n[p])&&Ja(i,p,s,a,o);e.push(i)}}return Xa(l,s,a)};Uu.filter=function(t){var e,n,r,i=[];"function"!=typeof t&&(t=W(t));for(var o=0,a=this.length;a>o;o++){i.push(e=[]);for(var n=this[o],s=0,l=n.length;l>s;s++)(r=n[s])&&t.call(r,r.__data__,s,o)&&e.push(r)}return Xa(i,this.namespace,this.id)};Uu.tween=function(t,e){var n=this.id,r=this.namespace;return arguments.length<2?this.node()[r][n].tween.get(t):q(this,null==e?function(e){e[r][n].tween.remove(t)}:function(i){i[r][n].tween.set(t,e)})};Uu.attr=function(t,e){function n(){this.removeAttribute(s)}function r(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?n:(t+="",function(){var e,n=this.getAttribute(s);return n!==t&&(e=a(n,t),function(t){this.setAttribute(s,e(t))})})}function o(t){return null==t?r:(t+="",function(){var e,n=this.getAttributeNS(s.space,s.local);return n!==t&&(e=a(n,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var a="transform"==t?Ui:xi,s=is.ns.qualify(t);return Ga(this,"attr."+t,e,s.local?o:i)};Uu.attrTween=function(t,e){function n(t,n){var r=e.call(this,t,n,this.getAttribute(i));return r&&function(t){this.setAttribute(i,r(t))}}function r(t,n){var r=e.call(this,t,n,this.getAttributeNS(i.space,i.local));return r&&function(t){this.setAttributeNS(i.space,i.local,r(t))}}var i=is.ns.qualify(t);return this.tween("attr."+t,i.local?r:n)};Uu.style=function(t,e,n){function r(){this.style.removeProperty(t)}function i(e){return null==e?r:(e+="",function(){var r,i=us.getComputedStyle(this,null).getPropertyValue(t);return i!==e&&(r=xi(i,e),function(e){this.style.setProperty(t,r(e),n)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(n in t)this.style(n,t[n],e);return this}n=""}return Ga(this,"style."+t,e,i)};Uu.styleTween=function(t,e,n){function r(r,i){var o=e.call(this,r,i,us.getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),n)}}arguments.length<3&&(n="");return this.tween("style."+t,r)};Uu.text=function(t){return Ga(this,"text",t,$a)};Uu.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})};Uu.ease=function(t){var e=this.id,n=this.namespace;if(arguments.length<1)return this.node()[n][e].ease;"function"!=typeof t&&(t=is.ease.apply(is,arguments));return q(this,function(r){r[n][e].ease=t})};Uu.delay=function(t){var e=this.id,n=this.namespace;return arguments.length<1?this.node()[n][e].delay:q(this,"function"==typeof t?function(r,i,o){r[n][e].delay=+t.call(r,r.__data__,i,o)}:(t=+t,function(r){r[n][e].delay=t}))};Uu.duration=function(t){var e=this.id,n=this.namespace;return arguments.length<1?this.node()[n][e].duration:q(this,"function"==typeof t?function(r,i,o){r[n][e].duration=Math.max(1,t.call(r,r.__data__,i,o))}:(t=Math.max(1,t),function(r){r[n][e].duration=t}))};Uu.each=function(t,e){var n=this.id,r=this.namespace;if(arguments.length<2){var i=zu,o=Wu;try{Wu=n;q(this,function(e,i,o){zu=e[r][n];t.call(e,e.__data__,i,o)})}finally{zu=i;Wu=o}}else q(this,function(i){var o=i[r][n];(o.event||(o.event=is.dispatch("start","end","interrupt"))).on(t,e)});return this};Uu.transition=function(){for(var t,e,n,r,i=this.id,o=++Bu,a=this.namespace,s=[],l=0,u=this.length;u>l;l++){s.push(t=[]);for(var e=this[l],c=0,f=e.length;f>c;c++){if(n=e[c]){r=n[a][i];Ja(n,c,a,o,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})}t.push(n)}}return Xa(s,a,o)};is.svg.axis=function(){function t(t){t.each(function(){var t,u=is.select(this),c=this.__chart__||n,f=this.__chart__=n.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,d=null==e?f.tickFormat?f.tickFormat.apply(f,s):De:e,p=u.selectAll(".tick").data(h,f),g=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Hs),m=is.transition(p.exit()).style("opacity",Hs).remove(),v=is.transition(p.order()).style("opacity",1),y=Math.max(i,0)+a,b=zo(f),x=u.selectAll(".domain").data([0]),w=(x.enter().append("path").attr("class","domain"),is.transition(x));g.append("line");g.append("text");var C,S,T,k,_=g.select("line"),M=v.select("line"),D=p.select("text").text(d),L=g.select("text"),A=v.select("text"),N="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r){t=Ka,C="x",T="y",S="x2",k="y2";D.attr("dy",0>N?"0em":".71em").style("text-anchor","middle");w.attr("d","M"+b[0]+","+N*o+"V0H"+b[1]+"V"+N*o)}else{t=Za,C="y",T="x",S="y2",k="x2";D.attr("dy",".32em").style("text-anchor",0>N?"end":"start");w.attr("d","M"+N*o+","+b[0]+"H0V"+b[1]+"H"+N*o)}_.attr(k,N*i);L.attr(T,N*y);M.attr(S,0).attr(k,N*i);A.attr(C,0).attr(T,N*y);if(f.rangeBand){var E=f,j=E.rangeBand()/2;c=f=function(t){return E(t)+j}}else c.rangeBand?c=f:m.call(t,f,c);g.call(t,c,f);v.call(t,f,f)})}var e,n=is.scale.linear(),r=Vu,i=6,o=6,a=3,s=[10],l=null;t.scale=function(e){if(!arguments.length)return n;n=e;return t};t.orient=function(e){if(!arguments.length)return r;r=e in Xu?e+"":Vu;return t};t.ticks=function(){if(!arguments.length)return s;s=arguments;return t};t.tickValues=function(e){if(!arguments.length)return l;l=e;return t};t.tickFormat=function(n){if(!arguments.length)return e;e=n;return t};t.tickSize=function(e){var n=arguments.length;if(!n)return i;i=+e;o=+arguments[n-1];return t};t.innerTickSize=function(e){if(!arguments.length)return i;i=+e;return t};t.outerTickSize=function(e){if(!arguments.length)return o;o=+e;return t};t.tickPadding=function(e){if(!arguments.length)return a;a=+e;return t};t.tickSubdivide=function(){return arguments.length&&t};return t};var Vu="bottom",Xu={top:1,right:1,bottom:1,left:1};is.svg.brush=function(){function t(o){o.each(function(){var o=is.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",i).on("touchstart.brush",i),a=o.selectAll(".background").data([0]);a.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");o.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=o.selectAll(".resize").data(p,De);s.exit().remove();s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Gu[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");s.style("display",t.empty()?"none":null);var c,f=is.transition(o),h=is.transition(a);if(l){c=zo(l);h.attr("x",c[0]).attr("width",c[1]-c[0]);n(f)}if(u){c=zo(u);h.attr("y",c[0]).attr("height",c[1]-c[0]);r(f)}e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+c[+/e$/.test(t)]+","+f[+/^s/.test(t)]+")"})}function n(t){t.select(".extent").attr("x",c[0]);t.selectAll(".extent,.n>rect,.s>rect").attr("width",c[1]-c[0])}function r(t){t.select(".extent").attr("y",f[0]);t.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function i(){function i(){if(32==is.event.keyCode){if(!D){y=null;A[0]-=c[1];A[1]-=f[1];D=2}S()}}function p(){if(32==is.event.keyCode&&2==D){A[0]+=c[1];A[1]+=f[1];D=0;S()}}function g(){var t=is.mouse(x),i=!1;if(b){t[0]+=b[0];t[1]+=b[1]}if(!D)if(is.event.altKey){y||(y=[(c[0]+c[1])/2,(f[0]+f[1])/2]);A[0]=c[+(t[0]<y[0])];A[1]=f[+(t[1]<y[1])]}else y=null;if(_&&m(t,l,0)){n(T);i=!0}if(M&&m(t,u,1)){r(T);i=!0}if(i){e(T);C({type:"brush",mode:D?"move":"resize"})}}function m(t,e,n){var r,i,s=zo(e),l=s[0],u=s[1],p=A[n],g=n?f:c,m=g[1]-g[0];if(D){l-=p;u-=m+p}r=(n?d:h)?Math.max(l,Math.min(u,t[n])):t[n];if(D)i=(r+=p)+m;else{y&&(p=Math.max(l,Math.min(u,2*y[n]-r)));if(r>p){i=r;r=p}else i=p}if(g[0]!=r||g[1]!=i){n?a=null:o=null;g[0]=r;g[1]=i;return!0}}function v(){g();T.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null);is.select("body").style("cursor",null);N.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);L();C({type:"brushend"})}var y,b,x=this,w=is.select(is.event.target),C=s.of(x,arguments),T=is.select(x),k=w.datum(),_=!/^(n|s)$/.test(k)&&l,M=!/^(e|w)$/.test(k)&&u,D=w.classed("extent"),L=$(),A=is.mouse(x),N=is.select(us).on("keydown.brush",i).on("keyup.brush",p);is.event.changedTouches?N.on("touchmove.brush",g).on("touchend.brush",v):N.on("mousemove.brush",g).on("mouseup.brush",v);T.interrupt().selectAll("*").interrupt();if(D){A[0]=c[0]-A[0];A[1]=f[0]-A[1]}else if(k){var E=+/w$/.test(k),j=+/^n/.test(k);b=[c[1-E]-A[0],f[1-j]-A[1]];A[0]=c[E];A[1]=f[j]}else is.event.altKey&&(y=A.slice());T.style("pointer-events","none").selectAll(".resize").style("display",null);is.select("body").style("cursor",w.style("cursor"));C({type:"brushstart"});g()}var o,a,s=k(t,"brushstart","brush","brushend"),l=null,u=null,c=[0,0],f=[0,0],h=!0,d=!0,p=$u[0];t.event=function(t){t.each(function(){var t=s.of(this,arguments),e={x:c,y:f,i:o,j:a},n=this.__chart__||e;this.__chart__=e;if(Wu)is.select(this).transition().each("start.brush",function(){o=n.i;a=n.j;c=n.x;f=n.y;t({type:"brushstart"})}).tween("brush:brush",function(){var n=wi(c,e.x),r=wi(f,e.y);o=a=null;return function(i){c=e.x=n(i);f=e.y=r(i);t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i;a=e.j;t({type:"brush",mode:"resize"});t({type:"brushend"})});else{t({type:"brushstart"});t({type:"brush",mode:"resize"});t({type:"brushend"})}})};t.x=function(e){if(!arguments.length)return l;l=e;p=$u[!l<<1|!u];return t};t.y=function(e){if(!arguments.length)return u;u=e;p=$u[!l<<1|!u];return t};t.clamp=function(e){if(!arguments.length)return l&&u?[h,d]:l?h:u?d:null;l&&u?(h=!!e[0],d=!!e[1]):l?h=!!e:u&&(d=!!e);return t};t.extent=function(e){var n,r,i,s,h;if(!arguments.length){if(l)if(o)n=o[0],r=o[1];else{n=c[0],r=c[1];l.invert&&(n=l.invert(n),r=l.invert(r));n>r&&(h=n,n=r,r=h)}if(u)if(a)i=a[0],s=a[1];else{i=f[0],s=f[1];u.invert&&(i=u.invert(i),s=u.invert(s));i>s&&(h=i,i=s,s=h)}return l&&u?[[n,i],[r,s]]:l?[n,r]:u&&[i,s]}if(l){n=e[0],r=e[1];u&&(n=n[0],r=r[0]);o=[n,r];l.invert&&(n=l(n),r=l(r));n>r&&(h=n,n=r,r=h);(n!=c[0]||r!=c[1])&&(c=[n,r])}if(u){i=e[0],s=e[1];l&&(i=i[1],s=s[1]);a=[i,s];u.invert&&(i=u(i),s=u(s));i>s&&(h=i,i=s,s=h);(i!=f[0]||s!=f[1])&&(f=[i,s])}return t};t.clear=function(){if(!t.empty()){c=[0,0],f=[0,0];o=a=null}return t};t.empty=function(){return!!l&&c[0]==c[1]||!!u&&f[0]==f[1]};return is.rebind(t,s,"on")};var Gu={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},$u=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Yu=pl.format=xl.timeFormat,Ju=Yu.utc,Ku=Ju("%Y-%m-%dT%H:%M:%S.%LZ");Yu.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Qa:Ku;Qa.parse=function(t){var e=new Date(t);return isNaN(e)?null:e};Qa.toString=Ku.toString;pl.second=ze(function(t){return new gl(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()});pl.seconds=pl.second.range;pl.seconds.utc=pl.second.utc.range;pl.minute=ze(function(t){return new gl(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()});pl.minutes=pl.minute.range;pl.minutes.utc=pl.minute.utc.range;pl.hour=ze(function(t){var e=t.getTimezoneOffset()/60;return new gl(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()});pl.hours=pl.hour.range;pl.hours.utc=pl.hour.utc.range;pl.month=ze(function(t){t=pl.day(t);t.setDate(1);return t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()});pl.months=pl.month.range;pl.months.utc=pl.month.utc.range;var Zu=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Qu=[[pl.second,1],[pl.second,5],[pl.second,15],[pl.second,30],[pl.minute,1],[pl.minute,5],[pl.minute,15],[pl.minute,30],[pl.hour,1],[pl.hour,3],[pl.hour,6],[pl.hour,12],[pl.day,1],[pl.day,2],[pl.week,1],[pl.month,1],[pl.month,3],[pl.year,1]],tc=Yu.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Nn]]),ec={range:function(t,e,n){return is.range(Math.ceil(t/n)*n,+e,n).map(es)},floor:De,ceil:De};Qu.year=pl.year;pl.scale=function(){return ts(is.scale.linear(),Qu,tc)};var nc=Qu.map(function(t){return[t[0].utc,t[1]]}),rc=Ju.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Nn]]);nc.year=pl.year.utc;pl.scale.utc=function(){return ts(is.scale.linear(),nc,rc)};is.text=Le(function(t){return t.responseText});is.json=function(t,e){return Ae(t,"application/json",ns,e)};is.html=function(t,e){return Ae(t,"text/html",rs,e)};is.xml=Le(function(t){return t.responseXML});"function"==typeof t&&t.amd?t(is):"object"==typeof n&&n.exports&&(n.exports=is);this.d3=is}()},{}],14:[function(t){var e=t("jquery");(function(t,e){function n(e,n){var i,o,a,s=e.nodeName.toLowerCase();if("area"===s){i=e.parentNode;o=i.name;if(!e.href||!o||"map"!==i.nodeName.toLowerCase())return!1;a=t("img[usemap=#"+o+"]")[0];return!!a&&r(a)}return(/input|select|textarea|button|object/.test(s)?!e.disabled:"a"===s?e.href||n:n)&&r(e)}function r(e){return t.expr.filters.visible(e)&&!t(e).parents().addBack().filter(function(){return"hidden"===t.css(this,"visibility")}).length}var i=0,o=/^ui-id-\d+$/;t.ui=t.ui||{};t.extend(t.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});t.fn.extend({focus:function(e){return function(n,r){return"number"==typeof n?this.each(function(){var e=this;setTimeout(function(){t(e).focus();r&&r.call(e)},n)}):e.apply(this,arguments)}}(t.fn.focus),scrollParent:function(){var e;e=t.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(t.css(this,"position"))&&/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0);return/fixed/.test(this.css("position"))||!e.length?t(document):e},zIndex:function(n){if(n!==e)return this.css("zIndex",n);if(this.length)for(var r,i,o=t(this[0]);o.length&&o[0]!==document;){r=o.css("position");if("absolute"===r||"relative"===r||"fixed"===r){i=parseInt(o.css("zIndex"),10);if(!isNaN(i)&&0!==i)return i}o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&t(this).removeAttr("id")})}});t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(n){return!!t.data(n,e)}}):function(e,n,r){return!!t.data(e,r[3])},focusable:function(e){return n(e,!isNaN(t.attr(e,"tabindex")))},tabbable:function(e){var r=t.attr(e,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(e,!i)}});t("<a>").outerWidth(1).jquery||t.each(["Width","Height"],function(n,r){function i(e,n,r,i){t.each(o,function(){n-=parseFloat(t.css(e,"padding"+this))||0;r&&(n-=parseFloat(t.css(e,"border"+this+"Width"))||0);i&&(n-=parseFloat(t.css(e,"margin"+this))||0)});return n}var o="Width"===r?["Left","Right"]:["Top","Bottom"],a=r.toLowerCase(),s={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+r]=function(n){return n===e?s["inner"+r].call(this):this.each(function(){t(this).css(a,i(this,n)+"px")})};t.fn["outer"+r]=function(e,n){return"number"!=typeof e?s["outer"+r].call(this,e):this.each(function(){t(this).css(a,i(this,e,!0,n)+"px")})}});t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))});t("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(t.fn.removeData=function(e){return function(n){return arguments.length?e.call(this,t.camelCase(n)):e.call(this)}}(t.fn.removeData));t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());t.support.selectstart="onselectstart"in document.createElement("div");t.fn.extend({disableSelection:function(){return this.bind((t.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(t){t.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});t.extend(t.ui,{plugin:{add:function(e,n,r){var i,o=t.ui[e].prototype;for(i in r){o.plugins[i]=o.plugins[i]||[];o.plugins[i].push([n,r[i]])}},call:function(t,e,n){var r,i=t.plugins[e];if(i&&t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType)for(r=0;r<i.length;r++)t.options[i[r][0]]&&i[r][1].apply(t.element,n)}},hasScroll:function(e,n){if("hidden"===t(e).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;if(e[r]>0)return!0;e[r]=1;i=e[r]>0;e[r]=0;return i}})})(e)},{jquery:18}],15:[function(t){var e=t("jquery");t("./widget");(function(t){var e=!1;t(document).mouseup(function(){e=!1});t.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(n){if(!0===t.data(n.target,e.widgetName+".preventClickEvent")){t.removeData(n.target,e.widgetName+".preventClickEvent");n.stopImmediatePropagation();return!1}});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(!e){this._mouseStarted&&this._mouseUp(n);this._mouseDownEvent=n;var r=this,i=1===n.which,o="string"==typeof this.options.cancel&&n.target.nodeName?t(n.target).closest(this.options.cancel).length:!1;if(!i||o||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay;this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted){n.preventDefault();return!0}}!0===t.data(n.target,this.widgetName+".preventClickEvent")&&t.removeData(n.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(t){return r._mouseMove(t)};this._mouseUpDelegate=function(t){return r._mouseUp(t)};t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);n.preventDefault();e=!0;return!0}},_mouseMove:function(e){if(t.ui.ie&&(!document.documentMode||document.documentMode<9)&&!e.button)return this._mouseUp(e);if(this._mouseStarted){this._mouseDrag(e);return e.preventDefault()}if(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)){this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1;this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)}return!this._mouseStarted},_mouseUp:function(e){t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=!1;e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0);this._mouseStop(e)}return!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(e)},{"./widget":17,jquery:18}],16:[function(t){var e=t("jquery");t("./core");t("./mouse");t("./widget");(function(t){function e(t,e,n){return t>e&&e+n>t}function n(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display")) }t.widget("ui.sortable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?"x"===t.axis||n(this.items[0].item):!1;this.offset=this.element.offset();this._mouseInit();this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,n){if("disabled"===e){this.options[e]=n;this.widget().toggleClass("ui-sortable-disabled",!!n)}else t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,n){var r=null,i=!1,o=this;if(this.reverting)return!1;if(this.options.disabled||"static"===this.options.type)return!1;this._refreshItems(e);t(e.target).parents().each(function(){if(t.data(this,o.widgetName+"-item")===o){r=t(this);return!1}});t.data(e.target,o.widgetName+"-item")===o&&(r=t(e.target));if(!r)return!1;if(this.options.handle&&!n){t(this.options.handle,r).find("*").addBack().each(function(){this===e.target&&(i=!0)});if(!i)return!1}this.currentItem=r;this._removeCurrentsFromItems();return!0},_mouseStart:function(e,n,r){var i,o,a=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!==this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();a.containment&&this._setContainment();if(a.cursor&&"auto"!==a.cursor){o=this.document.find("body");this.storedCursor=o.css("cursor");o.css("cursor",a.cursor);this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)}if(a.opacity){this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity"));this.helper.css("opacity",a.opacity)}if(a.zIndex){this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex"));this.helper.css("zIndex",a.zIndex)}this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset());this._trigger("start",e,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",e,this._uiHash(this));t.ui.ddmanager&&(t.ui.ddmanager.current=this);t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return!0},_mouseDrag:function(e){var n,r,i,o,a=this.options,s=!1;this.position=this._generatePosition(e);this.positionAbs=this._convertPositionTo("absolute");this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){if(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName){this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=s=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=s=this.scrollParent[0].scrollTop-a.scrollSpeed);this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=s=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=s=this.scrollParent[0].scrollLeft-a.scrollSpeed)}else{e.pageY-t(document).scrollTop()<a.scrollSensitivity?s=t(document).scrollTop(t(document).scrollTop()-a.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<a.scrollSensitivity&&(s=t(document).scrollTop(t(document).scrollTop()+a.scrollSpeed));e.pageX-t(document).scrollLeft()<a.scrollSensitivity?s=t(document).scrollLeft(t(document).scrollLeft()-a.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<a.scrollSensitivity&&(s=t(document).scrollLeft(t(document).scrollLeft()+a.scrollSpeed))}s!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)}this.positionAbs=this._convertPositionTo("absolute");this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(n=this.items.length-1;n>=0;n--){r=this.items[n];i=r.item[0];o=this._intersectsWithPointer(r);if(o&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==i&&!t.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],i):!0)){this.direction=1===o?"down":"up";if("pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(e,r);this._trigger("change",e,this._uiHash());break}}this._contactContainers(e);t.ui.ddmanager&&t.ui.ddmanager.drag(this,e);this._trigger("sort",e,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(e,n){if(e){t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e);if(this.options.revert){var r=this,i=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft));o&&"y"!==o||(a.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop));this.reverting=!0;t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){r._clear(e)})}else this._clear(e,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("deactivate",null,this._uiHash(this));if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",null,this._uiHash(this));this.containers[e].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove();t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null});this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(e){var n=this._getItemsAsjQuery(e&&e.connected),r=[];e=e||{};t(n).each(function(){var n=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);n&&r.push((e.key||n[1]+"[]")+"="+(e.key&&e.expression?n[1]:n[2]))});!r.length&&e.key&&r.push(e.key+"=");return r.join("&")},toArray:function(e){var n=this._getItemsAsjQuery(e&&e.connected),r=[];e=e||{};n.each(function(){r.push(t(e.item||this).attr(e.attribute||"id")||"")});return r},_intersectsWith:function(t){var e=this.positionAbs.left,n=e+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,o=t.left,a=o+t.width,s=t.top,l=s+t.height,u=this.offset.click.top,c=this.offset.click.left,f="x"===this.options.axis||r+u>s&&l>r+u,h="y"===this.options.axis||e+c>o&&a>e+c,d=f&&h;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?d:o<e+this.helperProportions.width/2&&n-this.helperProportions.width/2<a&&s<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<l},_intersectsWithPointer:function(t){var n="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),r="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&&r,o=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return i?this.floating?a&&"right"===a||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(t){var n=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&r||"left"===o&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){this._refreshItems(t);this.refreshPositions();return this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function n(){s.push(this)}var r,i,o,a,s=[],l=[],u=this._connectWith();if(u&&e)for(r=u.length-1;r>=0;r--){o=t(u[r]);for(i=o.length-1;i>=0;i--){a=t.data(o[i],this.widgetFullName);a&&a!==this&&!a.options.disabled&&l.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}l.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(r=l.length-1;r>=0;r--)l[r][0].each(n);return t(s)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var n=0;n<e.length;n++)if(e[n]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[];this.containers=[this];var n,r,i,o,a,s,l,u,c=this.items,f=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],h=this._connectWith();if(h&&this.ready)for(n=h.length-1;n>=0;n--){i=t(h[n]);for(r=i.length-1;r>=0;r--){o=t.data(i[r],this.widgetFullName);if(o&&o!==this&&!o.options.disabled){f.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]);this.containers.push(o)}}}for(n=f.length-1;n>=0;n--){a=f[n][1];s=f[n][0];for(r=0,u=s.length;u>r;r++){l=t(s[r]);l.data(this.widgetName+"-item",a);c.push({item:l,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,o;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance===this.currentContainer||!this.currentContainer||r.item[0]===this.currentItem[0]){i=this.options.toleranceElement?t(this.options.toleranceElement,r.item):r.item;if(!e){r.width=i.outerWidth();r.height=i.outerHeight()}o=i.offset();r.left=o.left;r.top=o.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--){o=this.containers[n].element.offset();this.containers[n].containerCache.left=o.left;this.containers[n].containerCache.top=o.top;this.containers[n].containerCache.width=this.containers[n].element.outerWidth();this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(e){e=e||this;var n,r=e.options;if(!r.placeholder||r.placeholder.constructor===String){n=r.placeholder;r.placeholder={element:function(){var r=e.currentItem[0].nodeName.toLowerCase(),i=t("<"+r+">",e.document[0]).addClass(n||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");"tr"===r?e.currentItem.children().each(function(){t("<td>&#160;</td>",e.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)}):"img"===r&&i.attr("src",e.currentItem.attr("src"));n||i.css("visibility","hidden");return i},update:function(t,i){if(!n||r.forcePlaceholderSize){i.height()||i.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10));i.width()||i.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10))}}}}e.placeholder=t(r.placeholder.element.call(e.element,e.currentItem));e.currentItem.after(e.placeholder);r.placeholder.update(e,e.placeholder)},_contactContainers:function(r){var i,o,a,s,l,u,c,f,h,d,p=null,g=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(p&&t.contains(this.containers[i].element[0],p.element[0]))continue;p=this.containers[i];g=i}else if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",r,this._uiHash(this));this.containers[i].containerCache.over=0}if(p)if(1===this.containers.length){if(!this.containers[g].containerCache.over){this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}}else{a=1e4;s=null;d=p.floating||n(this.currentItem);l=d?"left":"top";u=d?"width":"height";c=this.positionAbs[l]+this.offset.click[l];for(o=this.items.length-1;o>=0;o--)if(t.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!d||e(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))){f=this.items[o].item.offset()[l];h=!1;if(Math.abs(f-c)>Math.abs(f+this.items[o][u]-c)){h=!0;f+=this.items[o][u]}if(Math.abs(f-c)<a){a=Math.abs(f-c);s=this.items[o];this.direction=h?"up":"down"}}if(!s&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;s?this._rearrange(r,s,null,!0):this._rearrange(r,null,this.containers[g].element,!0);this._trigger("change",r,this._uiHash());this.containers[g]._trigger("change",r,this._uiHash(this));this.currentContainer=this.containers[g];this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}},_createHelper:function(e){var n=this.options,r=t.isFunction(n.helper)?t(n.helper.apply(this.element[0],[e,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;r.parents("body").length||t("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]);r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")});(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width());(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height());return r},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" "));t.isArray(e)&&(e={left:+e[0],top:+e[1]||0});"left"in e&&(this.offset.click.left=e.left+this.margins.left);"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left);"top"in e&&(this.offset.click.top=e.top+this.margins.top);"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();if("absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])){e.left+=this.scrollParent.scrollLeft();e.top+=this.scrollParent.scrollTop()}(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0});return{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode);("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]);if(!/^(document|window|parent)$/.test(i.containment)){e=t(i.containment)[0];n=t(i.containment).offset();r="hidden"!==t(e).css("overflow");this.containment=[n.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(e,n){n||(n=this.position);var r="absolute"===e?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:i.scrollLeft())*r}},_generatePosition:function(e){var n,r,i=this.options,o=e.pageX,a=e.pageY,s="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(s[0].tagName);"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());if(this.originalPosition){if(this.containment){e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left);e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top);e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left);e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)}if(i.grid){n=this.originalPageY+Math.round((a-this.originalPageY)/i.grid[1])*i.grid[1];a=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n;r=this.originalPageX+Math.round((o-this.originalPageX)/i.grid[0])*i.grid[0];o=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r}}return{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:s.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:s.scrollLeft())}},_rearrange:function(t,e,n,r){n?n[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(t,e){function n(t,e,n){return function(r){n._trigger(t,r,e._uiHash(e))}}this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)("auto"===this._storedCSS[r]||"static"===this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!e&&i.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))});!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||i.push(function(t){this._trigger("update",t,this._uiHash())});if(this!==this.currentContainer&&!e){i.push(function(t){this._trigger("remove",t,this._uiHash())});i.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer));i.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer))}for(r=this.containers.length-1;r>=0;r--){e||i.push(n("deactivate",this,this.containers[r]));if(this.containers[r].containerCache.over){i.push(n("out",this,this.containers[r]));this.containers[r].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",t,this._uiHash());for(r=0;r<i.length;r++)i[r].call(this,t);this._trigger("stop",t,this._uiHash())}this.fromOutside=!1;return!1}e||this._trigger("beforeStop",t,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!==this.currentItem[0]&&this.helper.remove();this.helper=null;if(!e){for(r=0;r<i.length;r++)i[r].call(this,t);this._trigger("stop",t,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var n=e||this;return{helper:n.helper,placeholder:n.placeholder||t([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:e?e.element:null}}})})(e)},{"./core":14,"./mouse":15,"./widget":17,jquery:18}],17:[function(t){var e=t("jquery");(function(t,e){var n=0,r=Array.prototype.slice,i=t.cleanData;t.cleanData=function(e){for(var n,r=0;null!=(n=e[r]);r++)try{t(n).triggerHandler("remove")}catch(o){}i(e)};t.widget=function(e,n,r){var i,o,a,s,l={},u=e.split(".")[0];e=e.split(".")[1];i=u+"-"+e;if(!r){r=n;n=t.Widget}t.expr[":"][i.toLowerCase()]=function(e){return!!t.data(e,i)};t[u]=t[u]||{};o=t[u][e];a=t[u][e]=function(t,e){if(!this._createWidget)return new a(t,e);arguments.length&&this._createWidget(t,e);return void 0};t.extend(a,o,{version:r.version,_proto:t.extend({},r),_childConstructors:[]});s=new n;s.options=t.widget.extend({},s.options);t.each(r,function(e,r){l[e]=t.isFunction(r)?function(){var t=function(){return n.prototype[e].apply(this,arguments)},i=function(t){return n.prototype[e].apply(this,t)};return function(){var e,n=this._super,o=this._superApply;this._super=t;this._superApply=i;e=r.apply(this,arguments);this._super=n;this._superApply=o;return e}}():r});a.prototype=t.widget.extend(s,{widgetEventPrefix:o?s.widgetEventPrefix||e:e},l,{constructor:a,namespace:u,widgetName:e,widgetFullName:i});if(o){t.each(o._childConstructors,function(e,n){var r=n.prototype;t.widget(r.namespace+"."+r.widgetName,a,n._proto)});delete o._childConstructors}else n._childConstructors.push(a);t.widget.bridge(e,a)};t.widget.extend=function(n){for(var i,o,a=r.call(arguments,1),s=0,l=a.length;l>s;s++)for(i in a[s]){o=a[s][i];a[s].hasOwnProperty(i)&&o!==e&&(n[i]=t.isPlainObject(o)?t.isPlainObject(n[i])?t.widget.extend({},n[i],o):t.widget.extend({},o):o)}return n};t.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;t.fn[n]=function(a){var s="string"==typeof a,l=r.call(arguments,1),u=this;a=!s&&l.length?t.widget.extend.apply(null,[a].concat(l)):a;this.each(s?function(){var r,i=t.data(this,o);if(!i)return t.error("cannot call methods on "+n+" prior to initialization; attempted to call method '"+a+"'");if(!t.isFunction(i[a])||"_"===a.charAt(0))return t.error("no such method '"+a+"' for "+n+" widget instance");r=i[a].apply(i,l);if(r!==i&&r!==e){u=r&&r.jquery?u.pushStack(r.get()):r;return!1}}:function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new i(a,this))});return u}};t.Widget=function(){};t.Widget._childConstructors=[];t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,r){r=t(r||this.defaultElement||this)[0];this.element=t(r);this.uuid=n++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=t.widget.extend({},this.options,this._getCreateOptions(),e);this.bindings=t();this.hoverable=t();this.focusable=t();if(r!==this){t.data(r,this.widgetFullName,this);this._on(!0,this.element,{remove:function(t){t.target===r&&this.destroy()}});this.document=t(r.style?r.ownerDocument:r.document||r);this.window=t(this.document[0].defaultView||this.document[0].parentWindow)}this._create();this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(n,r){var i,o,a,s=n;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof n){s={};i=n.split(".");n=i.shift();if(i.length){o=s[n]=t.widget.extend({},this.options[n]);for(a=0;a<i.length-1;a++){o[i[a]]=o[i[a]]||{};o=o[i[a]]}n=i.pop();if(1===arguments.length)return o[n]===e?null:o[n];o[n]=r}else{if(1===arguments.length)return this.options[n]===e?null:this.options[n];s[n]=r}}this._setOptions(s);return this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){this.options[t]=e;if("disabled"===t){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(e,n,r){var i,o=this;if("boolean"!=typeof e){r=n;n=e;e=!1}if(r){n=i=t(n);this.bindings=this.bindings.add(n)}else{r=n;n=this.element;i=this.widget()}t.each(r,function(r,a){function s(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(s.guid=a.guid=a.guid||s.guid||t.guid++);var l=r.match(/^(\w+)\s*(.*)$/),u=l[1]+o.eventNamespace,c=l[2];c?i.delegate(c,u,s):n.bind(u,s)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;t.unbind(e).undelegate(e)},_delay:function(t,e){function n(){return("string"==typeof t?r[t]:t).apply(r,arguments)}var r=this;return setTimeout(n,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e);this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e);this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,n,r){var i,o,a=this.options[e];r=r||{};n=t.Event(n);n.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();n.target=this.element[0];o=n.originalEvent;if(o)for(i in o)i in n||(n[i]=o[i]);this.element.trigger(n,r);return!(t.isFunction(a)&&a.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}};t.each({show:"fadeIn",hide:"fadeOut"},function(e,n){t.Widget.prototype["_"+e]=function(r,i,o){"string"==typeof i&&(i={effect:i});var a,s=i?i===!0||"number"==typeof i?n:i.effect||n:e;i=i||{};"number"==typeof i&&(i={duration:i});a=!t.isEmptyObject(i);i.complete=o;i.delay&&r.delay(i.delay);a&&t.effects&&t.effects.effect[s]?r[e](i):s!==e&&r[s]?r[s](i.duration,i.easing,o):r.queue(function(n){t(this)[e]();o&&o.call(r[0]);n()})}})})(e)},{jquery:18}],18:[function(e,n){(function(t,e){"object"==typeof n&&"object"==typeof n.exports?n.exports=t.document?e(t,!0):function(t){if(!t.document)throw new Error("jQuery requires a window with a document");return e(t)}:e(t)})("undefined"!=typeof window?window:this,function(e,n){function r(t){var e=t.length,n=oe.type(t);return"function"===n||oe.isWindow(t)?!1:1===t.nodeType&&e?!0:"array"===n||0===e||"number"==typeof e&&e>0&&e-1 in t}function i(t,e,n){if(oe.isFunction(e))return oe.grep(t,function(t,r){return!!e.call(t,r,t)!==n});if(e.nodeType)return oe.grep(t,function(t){return t===e!==n});if("string"==typeof e){if(de.test(e))return oe.filter(e,t,n);e=oe.filter(e,t)}return oe.grep(t,function(t){return oe.inArray(t,e)>=0!==n})}function o(t,e){do t=t[e];while(t&&1!==t.nodeType);return t}function a(t){var e=we[t]={};oe.each(t.match(xe)||[],function(t,n){e[n]=!0});return e}function s(){if(ge.addEventListener){ge.removeEventListener("DOMContentLoaded",l,!1);e.removeEventListener("load",l,!1)}else{ge.detachEvent("onreadystatechange",l);e.detachEvent("onload",l)}}function l(){if(ge.addEventListener||"load"===event.type||"complete"===ge.readyState){s();oe.ready()}}function u(t,e,n){if(void 0===n&&1===t.nodeType){var r="data-"+e.replace(_e,"-$1").toLowerCase();n=t.getAttribute(r);if("string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:ke.test(n)?oe.parseJSON(n):n}catch(i){}oe.data(t,e,n)}else n=void 0}return n}function c(t){var e;for(e in t)if(("data"!==e||!oe.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}function f(t,e,n,r){if(oe.acceptData(t)){var i,o,a=oe.expando,s=t.nodeType,l=s?oe.cache:t,u=s?t[a]:t[a]&&a; if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof e){u||(u=s?t[a]=Y.pop()||oe.guid++:a);l[u]||(l[u]=s?{}:{toJSON:oe.noop});("object"==typeof e||"function"==typeof e)&&(r?l[u]=oe.extend(l[u],e):l[u].data=oe.extend(l[u].data,e));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==n&&(o[oe.camelCase(e)]=n);if("string"==typeof e){i=o[e];null==i&&(i=o[oe.camelCase(e)])}else i=o;return i}}}function h(t,e,n){if(oe.acceptData(t)){var r,i,o=t.nodeType,a=o?oe.cache:t,s=o?t[oe.expando]:oe.expando;if(a[s]){if(e){r=n?a[s]:a[s].data;if(r){if(oe.isArray(e))e=e.concat(oe.map(e,oe.camelCase));else if(e in r)e=[e];else{e=oe.camelCase(e);e=e in r?[e]:e.split(" ")}i=e.length;for(;i--;)delete r[e[i]];if(n?!c(r):!oe.isEmptyObject(r))return}}if(!n){delete a[s].data;if(!c(a[s]))return}o?oe.cleanData([t],!0):re.deleteExpando||a!=a.window?delete a[s]:a[s]=null}}}function d(){return!0}function p(){return!1}function g(){try{return ge.activeElement}catch(t){}}function m(t){var e=Oe.split("|"),n=t.createDocumentFragment();if(n.createElement)for(;e.length;)n.createElement(e.pop());return n}function v(t,e){var n,r,i=0,o=typeof t.getElementsByTagName!==Te?t.getElementsByTagName(e||"*"):typeof t.querySelectorAll!==Te?t.querySelectorAll(e||"*"):void 0;if(!o)for(o=[],n=t.childNodes||t;null!=(r=n[i]);i++)!e||oe.nodeName(r,e)?o.push(r):oe.merge(o,v(r,e));return void 0===e||e&&oe.nodeName(t,e)?oe.merge([t],o):o}function y(t){Ne.test(t.type)&&(t.defaultChecked=t.checked)}function b(t,e){return oe.nodeName(t,"table")&&oe.nodeName(11!==e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function x(t){t.type=(null!==oe.find.attr(t,"type"))+"/"+t.type;return t}function w(t){var e=$e.exec(t.type);e?t.type=e[1]:t.removeAttribute("type");return t}function C(t,e){for(var n,r=0;null!=(n=t[r]);r++)oe._data(n,"globalEval",!e||oe._data(e[r],"globalEval"))}function S(t,e){if(1===e.nodeType&&oe.hasData(t)){var n,r,i,o=oe._data(t),a=oe._data(e,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++)oe.event.add(e,n,s[n][r])}a.data&&(a.data=oe.extend({},a.data))}}function T(t,e){var n,r,i;if(1===e.nodeType){n=e.nodeName.toLowerCase();if(!re.noCloneEvent&&e[oe.expando]){i=oe._data(e);for(r in i.events)oe.removeEvent(e,r,i.handle);e.removeAttribute(oe.expando)}if("script"===n&&e.text!==t.text){x(e).text=t.text;w(e)}else if("object"===n){e.parentNode&&(e.outerHTML=t.outerHTML);re.html5Clone&&t.innerHTML&&!oe.trim(e.innerHTML)&&(e.innerHTML=t.innerHTML)}else if("input"===n&&Ne.test(t.type)){e.defaultChecked=e.checked=t.checked;e.value!==t.value&&(e.value=t.value)}else"option"===n?e.defaultSelected=e.selected=t.defaultSelected:("input"===n||"textarea"===n)&&(e.defaultValue=t.defaultValue)}}function k(t,n){var r,i=oe(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:oe.css(i[0],"display");i.detach();return o}function _(t){var e=ge,n=tn[t];if(!n){n=k(t,e);if("none"===n||!n){Qe=(Qe||oe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(e.documentElement);e=(Qe[0].contentWindow||Qe[0].contentDocument).document;e.write();e.close();n=k(t,e);Qe.detach()}tn[t]=n}return n}function M(t,e){return{get:function(){var n=t();if(null!=n){if(!n)return(this.get=e).apply(this,arguments);delete this.get}}}}function D(t,e){if(e in t)return e;for(var n=e.charAt(0).toUpperCase()+e.slice(1),r=e,i=pn.length;i--;){e=pn[i]+n;if(e in t)return e}return r}function L(t,e){for(var n,r,i,o=[],a=0,s=t.length;s>a;a++){r=t[a];if(r.style){o[a]=oe._data(r,"olddisplay");n=r.style.display;if(e){o[a]||"none"!==n||(r.style.display="");""===r.style.display&&Le(r)&&(o[a]=oe._data(r,"olddisplay",_(r.nodeName)))}else{i=Le(r);(n&&"none"!==n||!i)&&oe._data(r,"olddisplay",i?n:oe.css(r,"display"))}}}for(a=0;s>a;a++){r=t[a];r.style&&(e&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=e?o[a]||"":"none"))}return t}function A(t,e,n){var r=cn.exec(e);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):e}function N(t,e,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===e?1:0,a=0;4>o;o+=2){"margin"===n&&(a+=oe.css(t,n+De[o],!0,i));if(r){"content"===n&&(a-=oe.css(t,"padding"+De[o],!0,i));"margin"!==n&&(a-=oe.css(t,"border"+De[o]+"Width",!0,i))}else{a+=oe.css(t,"padding"+De[o],!0,i);"padding"!==n&&(a+=oe.css(t,"border"+De[o]+"Width",!0,i))}}return a}function E(t,e,n){var r=!0,i="width"===e?t.offsetWidth:t.offsetHeight,o=en(t),a=re.boxSizing&&"border-box"===oe.css(t,"boxSizing",!1,o);if(0>=i||null==i){i=nn(t,e,o);(0>i||null==i)&&(i=t.style[e]);if(on.test(i))return i;r=a&&(re.boxSizingReliable()||i===t.style[e]);i=parseFloat(i)||0}return i+N(t,e,n||(a?"border":"content"),r,o)+"px"}function j(t,e,n,r,i){return new j.prototype.init(t,e,n,r,i)}function I(){setTimeout(function(){gn=void 0});return gn=oe.now()}function P(t,e){var n,r={height:t},i=0;e=e?1:0;for(;4>i;i+=2-e){n=De[i];r["margin"+n]=r["padding"+n]=t}e&&(r.opacity=r.width=t);return r}function H(t,e,n){for(var r,i=(wn[e]||[]).concat(wn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,e,t))return r}function O(t,e,n){var r,i,o,a,s,l,u,c,f=this,h={},d=t.style,p=t.nodeType&&Le(t),g=oe._data(t,"fxshow");if(!n.queue){s=oe._queueHooks(t,"fx");if(null==s.unqueued){s.unqueued=0;l=s.empty.fire;s.empty.fire=function(){s.unqueued||l()}}s.unqueued++;f.always(function(){f.always(function(){s.unqueued--;oe.queue(t,"fx").length||s.empty.fire()})})}if(1===t.nodeType&&("height"in e||"width"in e)){n.overflow=[d.overflow,d.overflowX,d.overflowY];u=oe.css(t,"display");c="none"===u?oe._data(t,"olddisplay")||_(t.nodeName):u;"inline"===c&&"none"===oe.css(t,"float")&&(re.inlineBlockNeedsLayout&&"inline"!==_(t.nodeName)?d.zoom=1:d.display="inline-block")}if(n.overflow){d.overflow="hidden";re.shrinkWrapBlocks()||f.always(function(){d.overflow=n.overflow[0];d.overflowX=n.overflow[1];d.overflowY=n.overflow[2]})}for(r in e){i=e[r];if(vn.exec(i)){delete e[r];o=o||"toggle"===i;if(i===(p?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;p=!0}h[r]=g&&g[r]||oe.style(t,r)}else u=void 0}if(oe.isEmptyObject(h))"inline"===("none"===u?_(t.nodeName):u)&&(d.display=u);else{g?"hidden"in g&&(p=g.hidden):g=oe._data(t,"fxshow",{});o&&(g.hidden=!p);p?oe(t).show():f.done(function(){oe(t).hide()});f.done(function(){var e;oe._removeData(t,"fxshow");for(e in h)oe.style(t,e,h[e])});for(r in h){a=H(p?g[r]:0,r,f);if(!(r in g)){g[r]=a.start;if(p){a.end=a.start;a.start="width"===r||"height"===r?1:0}}}}}function F(t,e){var n,r,i,o,a;for(n in t){r=oe.camelCase(n);i=e[r];o=t[n];if(oe.isArray(o)){i=o[1];o=t[n]=o[0]}if(n!==r){t[r]=o;delete t[n]}a=oe.cssHooks[r];if(a&&"expand"in a){o=a.expand(o);delete t[r];for(n in o)if(!(n in t)){t[n]=o[n];e[n]=i}}else e[r]=i}}function R(t,e,n){var r,i,o=0,a=xn.length,s=oe.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var e=gn||I(),n=Math.max(0,u.startTime+u.duration-e),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);s.notifyWith(t,[u,o,n]);if(1>o&&l)return n;s.resolveWith(t,[u]);return!1},u=s.promise({elem:t,props:oe.extend({},e),opts:oe.extend(!0,{specialEasing:{}},n),originalProperties:e,originalOptions:n,startTime:gn||I(),duration:n.duration,tweens:[],createTween:function(e,n){var r=oe.Tween(t,u.opts,e,n,u.opts.specialEasing[e]||u.opts.easing);u.tweens.push(r);return r},stop:function(e){var n=0,r=e?u.tweens.length:0;if(i)return this;i=!0;for(;r>n;n++)u.tweens[n].run(1);e?s.resolveWith(t,[u,e]):s.rejectWith(t,[u,e]);return this}}),c=u.props;F(c,u.opts.specialEasing);for(;a>o;o++){r=xn[o].call(u,t,c,u.opts);if(r)return r}oe.map(c,H,u);oe.isFunction(u.opts.start)&&u.opts.start.call(t,u);oe.fx.timer(oe.extend(l,{elem:t,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function W(t){return function(e,n){if("string"!=typeof e){n=e;e="*"}var r,i=0,o=e.toLowerCase().match(xe)||[];if(oe.isFunction(n))for(;r=o[i++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(t[r]=t[r]||[]).unshift(n)}else(t[r]=t[r]||[]).push(n)}}function z(t,e,n,r){function i(s){var l;o[s]=!0;oe.each(t[s]||[],function(t,s){var u=s(e,n,r);if("string"==typeof u&&!a&&!o[u]){e.dataTypes.unshift(u);i(u);return!1}return a?!(l=u):void 0});return l}var o={},a=t===Vn;return i(e.dataTypes[0])||!o["*"]&&i("*")}function q(t,e){var n,r,i=oe.ajaxSettings.flatOptions||{};for(r in e)void 0!==e[r]&&((i[r]?t:n||(n={}))[r]=e[r]);n&&oe.extend(!0,t,n);return t}function U(t,e,n){for(var r,i,o,a,s=t.contents,l=t.dataTypes;"*"===l[0];){l.shift();void 0===i&&(i=t.mimeType||e.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]||t.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return n[o]}}function B(t,e,n,r){var i,o,a,s,l,u={},c=t.dataTypes.slice();if(c[1])for(a in t.converters)u[a.toLowerCase()]=t.converters[a];o=c.shift();for(;o;){t.responseFields[o]&&(n[t.responseFields[o]]=e);!l&&r&&t.dataFilter&&(e=t.dataFilter(e,t.dataType));l=o;o=c.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){a=u[l+" "+o]||u["* "+o];if(!a)for(i in u){s=i.split(" ");if(s[1]===o){a=u[l+" "+s[0]]||u["* "+s[0]];if(a){if(a===!0)a=u[i];else if(u[i]!==!0){o=s[0];c.unshift(s[1])}break}}}if(a!==!0)if(a&&t["throws"])e=a(e);else try{e=a(e)}catch(f){return{state:"parsererror",error:a?f:"No conversion from "+l+" to "+o}}}}return{state:"success",data:e}}function V(t,e,n,r){var i;if(oe.isArray(e))oe.each(e,function(e,i){n||Yn.test(t)?r(t,i):V(t+"["+("object"==typeof i?e:"")+"]",i,n,r)});else if(n||"object"!==oe.type(e))r(t,e);else for(i in e)V(t+"["+i+"]",e[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function G(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $(t){return oe.isWindow(t)?t:9===t.nodeType?t.defaultView||t.parentWindow:!1}var Y=[],J=Y.slice,K=Y.concat,Z=Y.push,Q=Y.indexOf,te={},ee=te.toString,ne=te.hasOwnProperty,re={},ie="1.11.1",oe=function(t,e){return new oe.fn.init(t,e)},ae=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,se=/^-ms-/,le=/-([\da-z])/gi,ue=function(t,e){return e.toUpperCase()};oe.fn=oe.prototype={jquery:ie,constructor:oe,selector:"",length:0,toArray:function(){return J.call(this)},get:function(t){return null!=t?0>t?this[t+this.length]:this[t]:J.call(this)},pushStack:function(t){var e=oe.merge(this.constructor(),t);e.prevObject=this;e.context=this.context;return e},each:function(t,e){return oe.each(this,t,e)},map:function(t){return this.pushStack(oe.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return this.pushStack(J.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,n=+t+(0>t?e:0);return this.pushStack(n>=0&&e>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:Y.sort,splice:Y.splice};oe.extend=oe.fn.extend=function(){var t,e,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;if("boolean"==typeof a){u=a;a=arguments[s]||{};s++}"object"==typeof a||oe.isFunction(a)||(a={});if(s===l){a=this;s--}for(;l>s;s++)if(null!=(i=arguments[s]))for(r in i){t=a[r];n=i[r];if(a!==n)if(u&&n&&(oe.isPlainObject(n)||(e=oe.isArray(n)))){if(e){e=!1;o=t&&oe.isArray(t)?t:[]}else o=t&&oe.isPlainObject(t)?t:{};a[r]=oe.extend(u,o,n)}else void 0!==n&&(a[r]=n)}return a};oe.extend({expando:"jQuery"+(ie+Math.random()).replace(/\D/g,""),isReady:!0,error:function(t){throw new Error(t)},noop:function(){},isFunction:function(t){return"function"===oe.type(t)},isArray:Array.isArray||function(t){return"array"===oe.type(t)},isWindow:function(t){return null!=t&&t==t.window},isNumeric:function(t){return!oe.isArray(t)&&t-parseFloat(t)>=0},isEmptyObject:function(t){var e;for(e in t)return!1;return!0},isPlainObject:function(t){var e;if(!t||"object"!==oe.type(t)||t.nodeType||oe.isWindow(t))return!1;try{if(t.constructor&&!ne.call(t,"constructor")&&!ne.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(re.ownLast)for(e in t)return ne.call(t,e);for(e in t);return void 0===e||ne.call(t,e)},type:function(t){return null==t?t+"":"object"==typeof t||"function"==typeof t?te[ee.call(t)]||"object":typeof t},globalEval:function(t){t&&oe.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(t){return t.replace(se,"ms-").replace(le,ue)},nodeName:function(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()},each:function(t,e,n){var i,o=0,a=t.length,s=r(t);if(n)if(s)for(;a>o;o++){i=e.apply(t[o],n);if(i===!1)break}else for(o in t){i=e.apply(t[o],n);if(i===!1)break}else if(s)for(;a>o;o++){i=e.call(t[o],o,t[o]);if(i===!1)break}else for(o in t){i=e.call(t[o],o,t[o]);if(i===!1)break}return t},trim:function(t){return null==t?"":(t+"").replace(ae,"")},makeArray:function(t,e){var n=e||[];null!=t&&(r(Object(t))?oe.merge(n,"string"==typeof t?[t]:t):Z.call(n,t));return n},inArray:function(t,e,n){var r;if(e){if(Q)return Q.call(e,t,n);r=e.length;n=n?0>n?Math.max(0,r+n):n:0;for(;r>n;n++)if(n in e&&e[n]===t)return n}return-1},merge:function(t,e){for(var n=+e.length,r=0,i=t.length;n>r;)t[i++]=e[r++];if(n!==n)for(;void 0!==e[r];)t[i++]=e[r++];t.length=i;return t},grep:function(t,e,n){for(var r,i=[],o=0,a=t.length,s=!n;a>o;o++){r=!e(t[o],o);r!==s&&i.push(t[o])}return i},map:function(t,e,n){var i,o=0,a=t.length,s=r(t),l=[];if(s)for(;a>o;o++){i=e(t[o],o,n);null!=i&&l.push(i)}else for(o in t){i=e(t[o],o,n);null!=i&&l.push(i)}return K.apply([],l)},guid:1,proxy:function(t,e){var n,r,i;if("string"==typeof e){i=t[e];e=t;t=i}if(!oe.isFunction(t))return void 0;n=J.call(arguments,2);r=function(){return t.apply(e||this,n.concat(J.call(arguments)))};r.guid=t.guid=t.guid||oe.guid++;return r},now:function(){return+new Date},support:re});oe.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){te["[object "+e+"]"]=e.toLowerCase()});var ce=function(t){function e(t,e,n,r){var i,o,a,s,l,u,f,d,p,g;(e?e.ownerDocument||e:W)!==E&&N(e);e=e||E;n=n||[];if(!t||"string"!=typeof t)return n;if(1!==(s=e.nodeType)&&9!==s)return[];if(I&&!r){if(i=ye.exec(t))if(a=i[1]){if(9===s){o=e.getElementById(a);if(!o||!o.parentNode)return n;if(o.id===a){n.push(o);return n}}else if(e.ownerDocument&&(o=e.ownerDocument.getElementById(a))&&F(e,o)&&o.id===a){n.push(o);return n}}else{if(i[2]){Q.apply(n,e.getElementsByTagName(t));return n}if((a=i[3])&&w.getElementsByClassName&&e.getElementsByClassName){Q.apply(n,e.getElementsByClassName(a));return n}}if(w.qsa&&(!P||!P.test(t))){d=f=R;p=e;g=9===s&&t;if(1===s&&"object"!==e.nodeName.toLowerCase()){u=k(t);(f=e.getAttribute("id"))?d=f.replace(xe,"\\$&"):e.setAttribute("id",d);d="[id='"+d+"'] ";l=u.length;for(;l--;)u[l]=d+h(u[l]);p=be.test(t)&&c(e.parentNode)||e;g=u.join(",")}if(g)try{Q.apply(n,p.querySelectorAll(g));return n}catch(m){}finally{f||e.removeAttribute("id")}}}return M(t.replace(le,"$1"),e,n,r)}function n(){function t(n,r){e.push(n+" ")>C.cacheLength&&delete t[e.shift()];return t[n+" "]=r}var e=[];return t}function r(t){t[R]=!0;return t}function i(t){var e=E.createElement("div");try{return!!t(e)}catch(n){return!1}finally{e.parentNode&&e.parentNode.removeChild(e);e=null}}function o(t,e){for(var n=t.split("|"),r=t.length;r--;)C.attrHandle[n[r]]=e}function a(t,e){var n=e&&t,r=n&&1===t.nodeType&&1===e.nodeType&&(~e.sourceIndex||$)-(~t.sourceIndex||$);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===e)return-1;return t?1:-1}function s(t){return function(e){var n=e.nodeName.toLowerCase();return"input"===n&&e.type===t}}function l(t){return function(e){var n=e.nodeName.toLowerCase();return("input"===n||"button"===n)&&e.type===t}}function u(t){return r(function(e){e=+e;return r(function(n,r){for(var i,o=t([],n.length,e),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(t){return t&&typeof t.getElementsByTagName!==G&&t}function f(){}function h(t){for(var e=0,n=t.length,r="";n>e;e++)r+=t[e].value;return r}function d(t,e,n){var r=e.dir,i=n&&"parentNode"===r,o=q++;return e.first?function(e,n,o){for(;e=e[r];)if(1===e.nodeType||i)return t(e,n,o)}:function(e,n,a){var s,l,u=[z,o];if(a){for(;e=e[r];)if((1===e.nodeType||i)&&t(e,n,a))return!0}else for(;e=e[r];)if(1===e.nodeType||i){l=e[R]||(e[R]={});if((s=l[r])&&s[0]===z&&s[1]===o)return u[2]=s[2];l[r]=u;if(u[2]=t(e,n,a))return!0}}}function p(t){return t.length>1?function(e,n,r){for(var i=t.length;i--;)if(!t[i](e,n,r))return!1;return!0}:t[0]}function g(t,n,r){for(var i=0,o=n.length;o>i;i++)e(t,n[i],r);return r}function m(t,e,n,r,i){for(var o,a=[],s=0,l=t.length,u=null!=e;l>s;s++)if((o=t[s])&&(!n||n(o,r,i))){a.push(o);u&&e.push(s)}return a}function v(t,e,n,i,o,a){i&&!i[R]&&(i=v(i));o&&!o[R]&&(o=v(o,a));return r(function(r,a,s,l){var u,c,f,h=[],d=[],p=a.length,v=r||g(e||"*",s.nodeType?[s]:s,[]),y=!t||!r&&e?v:m(v,h,t,s,l),b=n?o||(r?t:p||i)?[]:a:y;n&&n(y,b,s,l);if(i){u=m(b,d);i(u,[],s,l);c=u.length;for(;c--;)(f=u[c])&&(b[d[c]]=!(y[d[c]]=f))}if(r){if(o||t){if(o){u=[];c=b.length;for(;c--;)(f=b[c])&&u.push(y[c]=f);o(null,b=[],u,l)}c=b.length;for(;c--;)(f=b[c])&&(u=o?ee.call(r,f):h[c])>-1&&(r[u]=!(a[u]=f))}}else{b=m(b===a?b.splice(p,b.length):b);o?o(null,a,b,l):Q.apply(a,b)}})}function y(t){for(var e,n,r,i=t.length,o=C.relative[t[0].type],a=o||C.relative[" "],s=o?1:0,l=d(function(t){return t===e},a,!0),u=d(function(t){return ee.call(e,t)>-1},a,!0),c=[function(t,n,r){return!o&&(r||n!==D)||((e=n).nodeType?l(t,n,r):u(t,n,r))}];i>s;s++)if(n=C.relative[t[s].type])c=[d(p(c),n)];else{n=C.filter[t[s].type].apply(null,t[s].matches);if(n[R]){r=++s;for(;i>r&&!C.relative[t[r].type];r++);return v(s>1&&p(c),s>1&&h(t.slice(0,s-1).concat({value:" "===t[s-2].type?"*":""})).replace(le,"$1"),n,r>s&&y(t.slice(s,r)),i>r&&y(t=t.slice(r)),i>r&&h(t))}c.push(n)}return p(c)}function b(t,n){var i=n.length>0,o=t.length>0,a=function(r,a,s,l,u){var c,f,h,d=0,p="0",g=r&&[],v=[],y=D,b=r||o&&C.find.TAG("*",u),x=z+=null==y?1:Math.random()||.1,w=b.length;u&&(D=a!==E&&a);for(;p!==w&&null!=(c=b[p]);p++){if(o&&c){f=0;for(;h=t[f++];)if(h(c,a,s)){l.push(c);break}u&&(z=x)}if(i){(c=!h&&c)&&d--;r&&g.push(c)}}d+=p;if(i&&p!==d){f=0;for(;h=n[f++];)h(g,v,a,s);if(r){if(d>0)for(;p--;)g[p]||v[p]||(v[p]=K.call(l));v=m(v)}Q.apply(l,v);u&&!r&&v.length>0&&d+n.length>1&&e.uniqueSort(l)}if(u){z=x;D=y}return g};return i?r(a):a}var x,w,C,S,T,k,_,M,D,L,A,N,E,j,I,P,H,O,F,R="sizzle"+-new Date,W=t.document,z=0,q=0,U=n(),B=n(),V=n(),X=function(t,e){t===e&&(A=!0);return 0},G="undefined",$=1<<31,Y={}.hasOwnProperty,J=[],K=J.pop,Z=J.push,Q=J.push,te=J.slice,ee=J.indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(this[e]===t)return e;return-1},ne="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",re="[\\x20\\t\\r\\n\\f]",ie="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",oe=ie.replace("w","w#"),ae="\\["+re+"*("+ie+")(?:"+re+"*([*^$|!~]?=)"+re+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+oe+"))|)"+re+"*\\]",se=":("+ie+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ae+")*)|.*)\\)|)",le=new RegExp("^"+re+"+|((?:^|[^\\\\])(?:\\\\.)*)"+re+"+$","g"),ue=new RegExp("^"+re+"*,"+re+"*"),ce=new RegExp("^"+re+"*([>+~]|"+re+")"+re+"*"),fe=new RegExp("="+re+"*([^\\]'\"]*?)"+re+"*\\]","g"),he=new RegExp(se),de=new RegExp("^"+oe+"$"),pe={ID:new RegExp("^#("+ie+")"),CLASS:new RegExp("^\\.("+ie+")"),TAG:new RegExp("^("+ie.replace("w","w*")+")"),ATTR:new RegExp("^"+ae),PSEUDO:new RegExp("^"+se),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+re+"*(even|odd|(([+-]|)(\\d*)n|)"+re+"*(?:([+-]|)"+re+"*(\\d+)|))"+re+"*\\)|)","i"),bool:new RegExp("^(?:"+ne+")$","i"),needsContext:new RegExp("^"+re+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+re+"*((?:-\\d)?\\d*)"+re+"*\\)|)(?=[^-]|$)","i")},ge=/^(?:input|select|textarea|button)$/i,me=/^h\d$/i,ve=/^[^{]+\{\s*\[native \w/,ye=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,be=/[+~]/,xe=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+re+"?|("+re+")|.)","ig"),Ce=function(t,e,n){var r="0x"+e-65536;return r!==r||n?e:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Q.apply(J=te.call(W.childNodes),W.childNodes);J[W.childNodes.length].nodeType}catch(Se){Q={apply:J.length?function(t,e){Z.apply(t,te.call(e))}:function(t,e){for(var n=t.length,r=0;t[n++]=e[r++];);t.length=n-1}}}w=e.support={};T=e.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return e?"HTML"!==e.nodeName:!1};N=e.setDocument=function(t){var e,n=t?t.ownerDocument||t:W,r=n.defaultView;if(n===E||9!==n.nodeType||!n.documentElement)return E;E=n;j=n.documentElement;I=!T(n);r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){N()},!1):r.attachEvent&&r.attachEvent("onunload",function(){N()}));w.attributes=i(function(t){t.className="i";return!t.getAttribute("className")});w.getElementsByTagName=i(function(t){t.appendChild(n.createComment(""));return!t.getElementsByTagName("*").length});w.getElementsByClassName=ve.test(n.getElementsByClassName)&&i(function(t){t.innerHTML="<div class='a'></div><div class='a i'></div>";t.firstChild.className="i";return 2===t.getElementsByClassName("i").length});w.getById=i(function(t){j.appendChild(t).id=R;return!n.getElementsByName||!n.getElementsByName(R).length});if(w.getById){C.find.ID=function(t,e){if(typeof e.getElementById!==G&&I){var n=e.getElementById(t);return n&&n.parentNode?[n]:[]}};C.filter.ID=function(t){var e=t.replace(we,Ce);return function(t){return t.getAttribute("id")===e}}}else{delete C.find.ID;C.filter.ID=function(t){var e=t.replace(we,Ce);return function(t){var n=typeof t.getAttributeNode!==G&&t.getAttributeNode("id");return n&&n.value===e}}}C.find.TAG=w.getElementsByTagName?function(t,e){return typeof e.getElementsByTagName!==G?e.getElementsByTagName(t):void 0}:function(t,e){var n,r=[],i=0,o=e.getElementsByTagName(t);if("*"===t){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o};C.find.CLASS=w.getElementsByClassName&&function(t,e){return typeof e.getElementsByClassName!==G&&I?e.getElementsByClassName(t):void 0};H=[];P=[];if(w.qsa=ve.test(n.querySelectorAll)){i(function(t){t.innerHTML="<select msallowclip=''><option selected=''></option></select>";t.querySelectorAll("[msallowclip^='']").length&&P.push("[*^$]="+re+"*(?:''|\"\")");t.querySelectorAll("[selected]").length||P.push("\\["+re+"*(?:value|"+ne+")");t.querySelectorAll(":checked").length||P.push(":checked")});i(function(t){var e=n.createElement("input");e.setAttribute("type","hidden");t.appendChild(e).setAttribute("name","D");t.querySelectorAll("[name=d]").length&&P.push("name"+re+"*[*^$|!~]?=");t.querySelectorAll(":enabled").length||P.push(":enabled",":disabled");t.querySelectorAll("*,:x");P.push(",.*:")})}(w.matchesSelector=ve.test(O=j.matches||j.webkitMatchesSelector||j.mozMatchesSelector||j.oMatchesSelector||j.msMatchesSelector))&&i(function(t){w.disconnectedMatch=O.call(t,"div");O.call(t,"[s!='']:x");H.push("!=",se)});P=P.length&&new RegExp(P.join("|"));H=H.length&&new RegExp(H.join("|"));e=ve.test(j.compareDocumentPosition);F=e||ve.test(j.contains)?function(t,e){var n=9===t.nodeType?t.documentElement:t,r=e&&e.parentNode;return t===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):t.compareDocumentPosition&&16&t.compareDocumentPosition(r)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1};X=e?function(t,e){if(t===e){A=!0;return 0}var r=!t.compareDocumentPosition-!e.compareDocumentPosition;if(r)return r;r=(t.ownerDocument||t)===(e.ownerDocument||e)?t.compareDocumentPosition(e):1;return 1&r||!w.sortDetached&&e.compareDocumentPosition(t)===r?t===n||t.ownerDocument===W&&F(W,t)?-1:e===n||e.ownerDocument===W&&F(W,e)?1:L?ee.call(L,t)-ee.call(L,e):0:4&r?-1:1}:function(t,e){if(t===e){A=!0;return 0}var r,i=0,o=t.parentNode,s=e.parentNode,l=[t],u=[e];if(!o||!s)return t===n?-1:e===n?1:o?-1:s?1:L?ee.call(L,t)-ee.call(L,e):0;if(o===s)return a(t,e);r=t;for(;r=r.parentNode;)l.unshift(r);r=e;for(;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===W?-1:u[i]===W?1:0};return n};e.matches=function(t,n){return e(t,null,null,n)};e.matchesSelector=function(t,n){(t.ownerDocument||t)!==E&&N(t);n=n.replace(fe,"='$1']");if(!(!w.matchesSelector||!I||H&&H.test(n)||P&&P.test(n)))try{var r=O.call(t,n);if(r||w.disconnectedMatch||t.document&&11!==t.document.nodeType)return r}catch(i){}return e(n,E,null,[t]).length>0};e.contains=function(t,e){(t.ownerDocument||t)!==E&&N(t);return F(t,e)};e.attr=function(t,e){(t.ownerDocument||t)!==E&&N(t);var n=C.attrHandle[e.toLowerCase()],r=n&&Y.call(C.attrHandle,e.toLowerCase())?n(t,e,!I):void 0;return void 0!==r?r:w.attributes||!I?t.getAttribute(e):(r=t.getAttributeNode(e))&&r.specified?r.value:null};e.error=function(t){throw new Error("Syntax error, unrecognized expression: "+t)};e.uniqueSort=function(t){var e,n=[],r=0,i=0;A=!w.detectDuplicates;L=!w.sortStable&&t.slice(0);t.sort(X);if(A){for(;e=t[i++];)e===t[i]&&(r=n.push(i));for(;r--;)t.splice(n[r],1)}L=null;return t};S=e.getText=function(t){var e,n="",r=0,i=t.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)n+=S(t)}else if(3===i||4===i)return t.nodeValue}else for(;e=t[r++];)n+=S(e);return n};C=e.selectors={cacheLength:50,createPseudo:r,match:pe,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){t[1]=t[1].replace(we,Ce);t[3]=(t[3]||t[4]||t[5]||"").replace(we,Ce);"~="===t[2]&&(t[3]=" "+t[3]+" ");return t.slice(0,4)},CHILD:function(t){t[1]=t[1].toLowerCase();if("nth"===t[1].slice(0,3)){t[3]||e.error(t[0]);t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3]));t[5]=+(t[7]+t[8]||"odd"===t[3])}else t[3]&&e.error(t[0]);return t},PSEUDO:function(t){var e,n=!t[6]&&t[2];if(pe.CHILD.test(t[0]))return null;if(t[3])t[2]=t[4]||t[5]||"";else if(n&&he.test(n)&&(e=k(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)){t[0]=t[0].slice(0,e);t[2]=n.slice(0,e)}return t.slice(0,3)}},filter:{TAG:function(t){var e=t.replace(we,Ce).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=U[t+" "];return e||(e=new RegExp("(^|"+re+")"+t+"("+re+"|$)"))&&U(t,function(t){return e.test("string"==typeof t.className&&t.className||typeof t.getAttribute!==G&&t.getAttribute("class")||"")})},ATTR:function(t,n,r){return function(i){var o=e.attr(i,t);if(null==o)return"!="===n;if(!n)return!0;o+="";return"="===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}},CHILD:function(t,e,n,r,i){var o="nth"!==t.slice(0,3),a="last"!==t.slice(-4),s="of-type"===e;return 1===r&&0===i?function(t){return!!t.parentNode}:function(e,n,l){var u,c,f,h,d,p,g=o!==a?"nextSibling":"previousSibling",m=e.parentNode,v=s&&e.nodeName.toLowerCase(),y=!l&&!s;if(m){if(o){for(;g;){f=e;for(;f=f[g];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===t&&!p&&"nextSibling"}return!0}p=[a?m.firstChild:m.lastChild];if(a&&y){c=m[R]||(m[R]={});u=c[t]||[];d=u[0]===z&&u[1];h=u[0]===z&&u[2];f=d&&m.childNodes[d];for(;f=++d&&f&&f[g]||(h=d=0)||p.pop();)if(1===f.nodeType&&++h&&f===e){c[t]=[z,d,h];break}}else if(y&&(u=(e[R]||(e[R]={}))[t])&&u[0]===z)h=u[1];else for(;f=++d&&f&&f[g]||(h=d=0)||p.pop();)if((s?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++h){y&&((f[R]||(f[R]={}))[t]=[z,h]);if(f===e)break}h-=i;return h===r||h%r===0&&h/r>=0}}},PSEUDO:function(t,n){var i,o=C.pseudos[t]||C.setFilters[t.toLowerCase()]||e.error("unsupported pseudo: "+t);if(o[R])return o(n);if(o.length>1){i=[t,t,"",n];return C.setFilters.hasOwnProperty(t.toLowerCase())?r(function(t,e){for(var r,i=o(t,n),a=i.length;a--;){r=ee.call(t,i[a]);t[r]=!(e[r]=i[a])}}):function(t){return o(t,0,i)}}return o}},pseudos:{not:r(function(t){var e=[],n=[],i=_(t.replace(le,"$1"));return i[R]?r(function(t,e,n,r){for(var o,a=i(t,null,r,[]),s=t.length;s--;)(o=a[s])&&(t[s]=!(e[s]=o))}):function(t,r,o){e[0]=t;i(e,null,o,n);return!n.pop()}}),has:r(function(t){return function(n){return e(t,n).length>0}}),contains:r(function(t){return function(e){return(e.textContent||e.innerText||S(e)).indexOf(t)>-1}}),lang:r(function(t){de.test(t||"")||e.error("unsupported lang: "+t);t=t.replace(we,Ce).toLowerCase();return function(e){var n;do if(n=I?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang")){n=n.toLowerCase();return n===t||0===n.indexOf(t+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var n=t.location&&t.location.hash;return n&&n.slice(1)===e.id},root:function(t){return t===j},focus:function(t){return t===E.activeElement&&(!E.hasFocus||E.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},enabled:function(t){return t.disabled===!1},disabled:function(t){return t.disabled===!0},checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){t.parentNode&&t.parentNode.selectedIndex;return t.selected===!0},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType<6)return!1;return!0},parent:function(t){return!C.pseudos.empty(t)},header:function(t){return me.test(t.nodeName)},input:function(t){return ge.test(t.nodeName)},button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},text:function(t){var e;return"input"===t.nodeName.toLowerCase()&&"text"===t.type&&(null==(e=t.getAttribute("type"))||"text"===e.toLowerCase())},first:u(function(){return[0]}),last:u(function(t,e){return[e-1]}),eq:u(function(t,e,n){return[0>n?n+e:n]}),even:u(function(t,e){for(var n=0;e>n;n+=2)t.push(n);return t}),odd:u(function(t,e){for(var n=1;e>n;n+=2)t.push(n);return t}),lt:u(function(t,e,n){for(var r=0>n?n+e:n;--r>=0;)t.push(r);return t}),gt:u(function(t,e,n){for(var r=0>n?n+e:n;++r<e;)t.push(r);return t})}};C.pseudos.nth=C.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})C.pseudos[x]=l(x);f.prototype=C.filters=C.pseudos;C.setFilters=new f;k=e.tokenize=function(t,n){var r,i,o,a,s,l,u,c=B[t+" "];if(c)return n?0:c.slice(0);s=t;l=[];u=C.preFilter;for(;s;){if(!r||(i=ue.exec(s))){i&&(s=s.slice(i[0].length)||s);l.push(o=[])}r=!1;if(i=ce.exec(s)){r=i.shift();o.push({value:r,type:i[0].replace(le," ")});s=s.slice(r.length)}for(a in C.filter)if((i=pe[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?e.error(t):B(t,l).slice(0)};_=e.compile=function(t,e){var n,r=[],i=[],o=V[t+" "];if(!o){e||(e=k(t));n=e.length;for(;n--;){o=y(e[n]);o[R]?r.push(o):i.push(o)}o=V(t,b(i,r));o.selector=t}return o};M=e.select=function(t,e,n,r){var i,o,a,s,l,u="function"==typeof t&&t,f=!r&&k(t=u.selector||t);n=n||[];if(1===f.length){o=f[0]=f[0].slice(0);if(o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===e.nodeType&&I&&C.relative[o[1].type]){e=(C.find.ID(a.matches[0].replace(we,Ce),e)||[])[0];if(!e)return n;u&&(e=e.parentNode);t=t.slice(o.shift().value.length)}i=pe.needsContext.test(t)?0:o.length;for(;i--;){a=o[i];if(C.relative[s=a.type])break;if((l=C.find[s])&&(r=l(a.matches[0].replace(we,Ce),be.test(o[0].type)&&c(e.parentNode)||e))){o.splice(i,1);t=r.length&&h(o);if(!t){Q.apply(n,r);return n}break}}}(u||_(t,f))(r,e,!I,n,be.test(t)&&c(e.parentNode)||e);return n};w.sortStable=R.split("").sort(X).join("")===R;w.detectDuplicates=!!A;N();w.sortDetached=i(function(t){return 1&t.compareDocumentPosition(E.createElement("div"))});i(function(t){t.innerHTML="<a href='#'></a>";return"#"===t.firstChild.getAttribute("href")})||o("type|href|height|width",function(t,e,n){return n?void 0:t.getAttribute(e,"type"===e.toLowerCase()?1:2)});w.attributes&&i(function(t){t.innerHTML="<input/>";t.firstChild.setAttribute("value",""); return""===t.firstChild.getAttribute("value")})||o("value",function(t,e,n){return n||"input"!==t.nodeName.toLowerCase()?void 0:t.defaultValue});i(function(t){return null==t.getAttribute("disabled")})||o(ne,function(t,e,n){var r;return n?void 0:t[e]===!0?e.toLowerCase():(r=t.getAttributeNode(e))&&r.specified?r.value:null});return e}(e);oe.find=ce;oe.expr=ce.selectors;oe.expr[":"]=oe.expr.pseudos;oe.unique=ce.uniqueSort;oe.text=ce.getText;oe.isXMLDoc=ce.isXML;oe.contains=ce.contains;var fe=oe.expr.match.needsContext,he=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,de=/^.[^:#\[\.,]*$/;oe.filter=function(t,e,n){var r=e[0];n&&(t=":not("+t+")");return 1===e.length&&1===r.nodeType?oe.find.matchesSelector(r,t)?[r]:[]:oe.find.matches(t,oe.grep(e,function(t){return 1===t.nodeType}))};oe.fn.extend({find:function(t){var e,n=[],r=this,i=r.length;if("string"!=typeof t)return this.pushStack(oe(t).filter(function(){for(e=0;i>e;e++)if(oe.contains(r[e],this))return!0}));for(e=0;i>e;e++)oe.find(t,r[e],n);n=this.pushStack(i>1?oe.unique(n):n);n.selector=this.selector?this.selector+" "+t:t;return n},filter:function(t){return this.pushStack(i(this,t||[],!1))},not:function(t){return this.pushStack(i(this,t||[],!0))},is:function(t){return!!i(this,"string"==typeof t&&fe.test(t)?oe(t):t||[],!1).length}});var pe,ge=e.document,me=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ve=oe.fn.init=function(t,e){var n,r;if(!t)return this;if("string"==typeof t){n="<"===t.charAt(0)&&">"===t.charAt(t.length-1)&&t.length>=3?[null,t,null]:me.exec(t);if(!n||!n[1]&&e)return!e||e.jquery?(e||pe).find(t):this.constructor(e).find(t);if(n[1]){e=e instanceof oe?e[0]:e;oe.merge(this,oe.parseHTML(n[1],e&&e.nodeType?e.ownerDocument||e:ge,!0));if(he.test(n[1])&&oe.isPlainObject(e))for(n in e)oe.isFunction(this[n])?this[n](e[n]):this.attr(n,e[n]);return this}r=ge.getElementById(n[2]);if(r&&r.parentNode){if(r.id!==n[2])return pe.find(t);this.length=1;this[0]=r}this.context=ge;this.selector=t;return this}if(t.nodeType){this.context=this[0]=t;this.length=1;return this}if(oe.isFunction(t))return"undefined"!=typeof pe.ready?pe.ready(t):t(oe);if(void 0!==t.selector){this.selector=t.selector;this.context=t.context}return oe.makeArray(t,this)};ve.prototype=oe.fn;pe=oe(ge);var ye=/^(?:parents|prev(?:Until|All))/,be={children:!0,contents:!0,next:!0,prev:!0};oe.extend({dir:function(t,e,n){for(var r=[],i=t[e];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!oe(i).is(n));){1===i.nodeType&&r.push(i);i=i[e]}return r},sibling:function(t,e){for(var n=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&n.push(t);return n}});oe.fn.extend({has:function(t){var e,n=oe(t,this),r=n.length;return this.filter(function(){for(e=0;r>e;e++)if(oe.contains(this,n[e]))return!0})},closest:function(t,e){for(var n,r=0,i=this.length,o=[],a=fe.test(t)||"string"!=typeof t?oe(t,e||this.context):0;i>r;r++)for(n=this[r];n&&n!==e;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&oe.find.matchesSelector(n,t))){o.push(n);break}return this.pushStack(o.length>1?oe.unique(o):o)},index:function(t){return t?"string"==typeof t?oe.inArray(this[0],oe(t)):oe.inArray(t.jquery?t[0]:t,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){return this.pushStack(oe.unique(oe.merge(this.get(),oe(t,e))))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}});oe.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return oe.dir(t,"parentNode")},parentsUntil:function(t,e,n){return oe.dir(t,"parentNode",n)},next:function(t){return o(t,"nextSibling")},prev:function(t){return o(t,"previousSibling")},nextAll:function(t){return oe.dir(t,"nextSibling")},prevAll:function(t){return oe.dir(t,"previousSibling")},nextUntil:function(t,e,n){return oe.dir(t,"nextSibling",n)},prevUntil:function(t,e,n){return oe.dir(t,"previousSibling",n)},siblings:function(t){return oe.sibling((t.parentNode||{}).firstChild,t)},children:function(t){return oe.sibling(t.firstChild)},contents:function(t){return oe.nodeName(t,"iframe")?t.contentDocument||t.contentWindow.document:oe.merge([],t.childNodes)}},function(t,e){oe.fn[t]=function(n,r){var i=oe.map(this,e,n);"Until"!==t.slice(-5)&&(r=n);r&&"string"==typeof r&&(i=oe.filter(r,i));if(this.length>1){be[t]||(i=oe.unique(i));ye.test(t)&&(i=i.reverse())}return this.pushStack(i)}});var xe=/\S+/g,we={};oe.Callbacks=function(t){t="string"==typeof t?we[t]||a(t):oe.extend({},t);var e,n,r,i,o,s,l=[],u=!t.once&&[],c=function(a){n=t.memory&&a;r=!0;o=s||0;s=0;i=l.length;e=!0;for(;l&&i>o;o++)if(l[o].apply(a[0],a[1])===!1&&t.stopOnFalse){n=!1;break}e=!1;l&&(u?u.length&&c(u.shift()):n?l=[]:f.disable())},f={add:function(){if(l){var r=l.length;(function o(e){oe.each(e,function(e,n){var r=oe.type(n);"function"===r?t.unique&&f.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})})(arguments);if(e)i=l.length;else if(n){s=r;c(n)}}return this},remove:function(){l&&oe.each(arguments,function(t,n){for(var r;(r=oe.inArray(n,l,r))>-1;){l.splice(r,1);if(e){i>=r&&i--;o>=r&&o--}}});return this},has:function(t){return t?oe.inArray(t,l)>-1:!(!l||!l.length)},empty:function(){l=[];i=0;return this},disable:function(){l=u=n=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;n||f.disable();return this},locked:function(){return!u},fireWith:function(t,n){if(l&&(!r||u)){n=n||[];n=[t,n.slice?n.slice():n];e?u.push(n):c(n)}return this},fire:function(){f.fireWith(this,arguments);return this},fired:function(){return!!r}};return f};oe.extend({Deferred:function(t){var e=[["resolve","done",oe.Callbacks("once memory"),"resolved"],["reject","fail",oe.Callbacks("once memory"),"rejected"],["notify","progress",oe.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){i.done(arguments).fail(arguments);return this},then:function(){var t=arguments;return oe.Deferred(function(n){oe.each(e,function(e,o){var a=oe.isFunction(t[e])&&t[e];i[o[1]](function(){var t=a&&a.apply(this,arguments);t&&oe.isFunction(t.promise)?t.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[t]:arguments)})});t=null}).promise()},promise:function(t){return null!=t?oe.extend(t,r):r}},i={};r.pipe=r.then;oe.each(e,function(t,o){var a=o[2],s=o[3];r[o[1]]=a.add;s&&a.add(function(){n=s},e[1^t][2].disable,e[2][2].lock);i[o[0]]=function(){i[o[0]+"With"](this===i?r:this,arguments);return this};i[o[0]+"With"]=a.fireWith});r.promise(i);t&&t.call(i,i);return i},when:function(t){var e,n,r,i=0,o=J.call(arguments),a=o.length,s=1!==a||t&&oe.isFunction(t.promise)?a:0,l=1===s?t:oe.Deferred(),u=function(t,n,r){return function(i){n[t]=this;r[t]=arguments.length>1?J.call(arguments):i;r===e?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1){e=new Array(a);n=new Array(a);r=new Array(a);for(;a>i;i++)o[i]&&oe.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,e)):--s}s||l.resolveWith(r,o);return l.promise()}});var Ce;oe.fn.ready=function(t){oe.ready.promise().done(t);return this};oe.extend({isReady:!1,readyWait:1,holdReady:function(t){t?oe.readyWait++:oe.ready(!0)},ready:function(t){if(t===!0?!--oe.readyWait:!oe.isReady){if(!ge.body)return setTimeout(oe.ready);oe.isReady=!0;if(!(t!==!0&&--oe.readyWait>0)){Ce.resolveWith(ge,[oe]);if(oe.fn.triggerHandler){oe(ge).triggerHandler("ready");oe(ge).off("ready")}}}}});oe.ready.promise=function(t){if(!Ce){Ce=oe.Deferred();if("complete"===ge.readyState)setTimeout(oe.ready);else if(ge.addEventListener){ge.addEventListener("DOMContentLoaded",l,!1);e.addEventListener("load",l,!1)}else{ge.attachEvent("onreadystatechange",l);e.attachEvent("onload",l);var n=!1;try{n=null==e.frameElement&&ge.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!oe.isReady){try{n.doScroll("left")}catch(t){return setTimeout(i,50)}s();oe.ready()}}()}}return Ce.promise(t)};var Se,Te="undefined";for(Se in oe(re))break;re.ownLast="0"!==Se;re.inlineBlockNeedsLayout=!1;oe(function(){var t,e,n,r;n=ge.getElementsByTagName("body")[0];if(n&&n.style){e=ge.createElement("div");r=ge.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(e);if(typeof e.style.zoom!==Te){e.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";re.inlineBlockNeedsLayout=t=3===e.offsetWidth;t&&(n.style.zoom=1)}n.removeChild(r)}});(function(){var t=ge.createElement("div");if(null==re.deleteExpando){re.deleteExpando=!0;try{delete t.test}catch(e){re.deleteExpando=!1}}t=null})();oe.acceptData=function(t){var e=oe.noData[(t.nodeName+" ").toLowerCase()],n=+t.nodeType||1;return 1!==n&&9!==n?!1:!e||e!==!0&&t.getAttribute("classid")===e};var ke=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,_e=/([A-Z])/g;oe.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(t){t=t.nodeType?oe.cache[t[oe.expando]]:t[oe.expando];return!!t&&!c(t)},data:function(t,e,n){return f(t,e,n)},removeData:function(t,e){return h(t,e)},_data:function(t,e,n){return f(t,e,n,!0)},_removeData:function(t,e){return h(t,e,!0)}});oe.fn.extend({data:function(t,e){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===t){if(this.length){i=oe.data(o);if(1===o.nodeType&&!oe._data(o,"parsedAttrs")){n=a.length;for(;n--;)if(a[n]){r=a[n].name;if(0===r.indexOf("data-")){r=oe.camelCase(r.slice(5));u(o,r,i[r])}}oe._data(o,"parsedAttrs",!0)}}return i}return"object"==typeof t?this.each(function(){oe.data(this,t)}):arguments.length>1?this.each(function(){oe.data(this,t,e)}):o?u(o,t,oe.data(o,t)):void 0},removeData:function(t){return this.each(function(){oe.removeData(this,t)})}});oe.extend({queue:function(t,e,n){var r;if(t){e=(e||"fx")+"queue";r=oe._data(t,e);n&&(!r||oe.isArray(n)?r=oe._data(t,e,oe.makeArray(n)):r.push(n));return r||[]}},dequeue:function(t,e){e=e||"fx";var n=oe.queue(t,e),r=n.length,i=n.shift(),o=oe._queueHooks(t,e),a=function(){oe.dequeue(t,e)};if("inprogress"===i){i=n.shift();r--}if(i){"fx"===e&&n.unshift("inprogress");delete o.stop;i.call(t,a,o)}!r&&o&&o.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return oe._data(t,n)||oe._data(t,n,{empty:oe.Callbacks("once memory").add(function(){oe._removeData(t,e+"queue");oe._removeData(t,n)})})}});oe.fn.extend({queue:function(t,e){var n=2;if("string"!=typeof t){e=t;t="fx";n--}return arguments.length<n?oe.queue(this[0],t):void 0===e?this:this.each(function(){var n=oe.queue(this,t,e);oe._queueHooks(this,t);"fx"===t&&"inprogress"!==n[0]&&oe.dequeue(this,t)})},dequeue:function(t){return this.each(function(){oe.dequeue(this,t)})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,e){var n,r=1,i=oe.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};if("string"!=typeof t){e=t;t=void 0}t=t||"fx";for(;a--;){n=oe._data(o[a],t+"queueHooks");if(n&&n.empty){r++;n.empty.add(s)}}s();return i.promise(e)}});var Me=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,De=["Top","Right","Bottom","Left"],Le=function(t,e){t=e||t;return"none"===oe.css(t,"display")||!oe.contains(t.ownerDocument,t)},Ae=oe.access=function(t,e,n,r,i,o,a){var s=0,l=t.length,u=null==n;if("object"===oe.type(n)){i=!0;for(s in n)oe.access(t,e,s,n[s],!0,o,a)}else if(void 0!==r){i=!0;oe.isFunction(r)||(a=!0);if(u)if(a){e.call(t,r);e=null}else{u=e;e=function(t,e,n){return u.call(oe(t),n)}}if(e)for(;l>s;s++)e(t[s],n,a?r:r.call(t[s],s,e(t[s],n)))}return i?t:u?e.call(t):l?e(t[0],n):o},Ne=/^(?:checkbox|radio)$/i;(function(){var t=ge.createElement("input"),e=ge.createElement("div"),n=ge.createDocumentFragment();e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";re.leadingWhitespace=3===e.firstChild.nodeType;re.tbody=!e.getElementsByTagName("tbody").length;re.htmlSerialize=!!e.getElementsByTagName("link").length;re.html5Clone="<:nav></:nav>"!==ge.createElement("nav").cloneNode(!0).outerHTML;t.type="checkbox";t.checked=!0;n.appendChild(t);re.appendChecked=t.checked;e.innerHTML="<textarea>x</textarea>";re.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue;n.appendChild(e);e.innerHTML="<input type='radio' checked='checked' name='t'/>";re.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked;re.noCloneEvent=!0;if(e.attachEvent){e.attachEvent("onclick",function(){re.noCloneEvent=!1});e.cloneNode(!0).click()}if(null==re.deleteExpando){re.deleteExpando=!0;try{delete e.test}catch(r){re.deleteExpando=!1}}})();(function(){var t,n,r=ge.createElement("div");for(t in{submit:!0,change:!0,focusin:!0}){n="on"+t;if(!(re[t+"Bubbles"]=n in e)){r.setAttribute(n,"t");re[t+"Bubbles"]=r.attributes[n].expando===!1}}r=null})();var Ee=/^(?:input|select|textarea)$/i,je=/^key/,Ie=/^(?:mouse|pointer|contextmenu)|click/,Pe=/^(?:focusinfocus|focusoutblur)$/,He=/^([^.]*)(?:\.(.+)|)$/;oe.event={global:{},add:function(t,e,n,r,i){var o,a,s,l,u,c,f,h,d,p,g,m=oe._data(t);if(m){if(n.handler){l=n;n=l.handler;i=l.selector}n.guid||(n.guid=oe.guid++);(a=m.events)||(a=m.events={});if(!(c=m.handle)){c=m.handle=function(t){return typeof oe===Te||t&&oe.event.triggered===t.type?void 0:oe.event.dispatch.apply(c.elem,arguments)};c.elem=t}e=(e||"").match(xe)||[""];s=e.length;for(;s--;){o=He.exec(e[s])||[];d=g=o[1];p=(o[2]||"").split(".").sort();if(d){u=oe.event.special[d]||{};d=(i?u.delegateType:u.bindType)||d;u=oe.event.special[d]||{};f=oe.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&oe.expr.match.needsContext.test(i),namespace:p.join(".")},l);if(!(h=a[d])){h=a[d]=[];h.delegateCount=0;u.setup&&u.setup.call(t,r,p,c)!==!1||(t.addEventListener?t.addEventListener(d,c,!1):t.attachEvent&&t.attachEvent("on"+d,c))}if(u.add){u.add.call(t,f);f.handler.guid||(f.handler.guid=n.guid)}i?h.splice(h.delegateCount++,0,f):h.push(f);oe.event.global[d]=!0}}t=null}},remove:function(t,e,n,r,i){var o,a,s,l,u,c,f,h,d,p,g,m=oe.hasData(t)&&oe._data(t);if(m&&(c=m.events)){e=(e||"").match(xe)||[""];u=e.length;for(;u--;){s=He.exec(e[u])||[];d=g=s[1];p=(s[2]||"").split(".").sort();if(d){f=oe.event.special[d]||{};d=(r?f.delegateType:f.bindType)||d;h=c[d]||[];s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=h.length;for(;o--;){a=h[o];if(!(!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector))){h.splice(o,1);a.selector&&h.delegateCount--;f.remove&&f.remove.call(t,a)}}if(l&&!h.length){f.teardown&&f.teardown.call(t,p,m.handle)!==!1||oe.removeEvent(t,d,m.handle);delete c[d]}}else for(d in c)oe.event.remove(t,d+e[u],n,r,!0)}if(oe.isEmptyObject(c)){delete m.handle;oe._removeData(t,"events")}}},trigger:function(t,n,r,i){var o,a,s,l,u,c,f,h=[r||ge],d=ne.call(t,"type")?t.type:t,p=ne.call(t,"namespace")?t.namespace.split("."):[];s=c=r=r||ge;if(3!==r.nodeType&&8!==r.nodeType&&!Pe.test(d+oe.event.triggered)){if(d.indexOf(".")>=0){p=d.split(".");d=p.shift();p.sort()}a=d.indexOf(":")<0&&"on"+d;t=t[oe.expando]?t:new oe.Event(d,"object"==typeof t&&t);t.isTrigger=i?2:3;t.namespace=p.join(".");t.namespace_re=t.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;t.result=void 0;t.target||(t.target=r);n=null==n?[t]:oe.makeArray(n,[t]);u=oe.event.special[d]||{};if(i||!u.trigger||u.trigger.apply(r,n)!==!1){if(!i&&!u.noBubble&&!oe.isWindow(r)){l=u.delegateType||d;Pe.test(l+d)||(s=s.parentNode);for(;s;s=s.parentNode){h.push(s);c=s}c===(r.ownerDocument||ge)&&h.push(c.defaultView||c.parentWindow||e)}f=0;for(;(s=h[f++])&&!t.isPropagationStopped();){t.type=f>1?l:u.bindType||d;o=(oe._data(s,"events")||{})[t.type]&&oe._data(s,"handle");o&&o.apply(s,n);o=a&&s[a];if(o&&o.apply&&oe.acceptData(s)){t.result=o.apply(s,n);t.result===!1&&t.preventDefault()}}t.type=d;if(!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(h.pop(),n)===!1)&&oe.acceptData(r)&&a&&r[d]&&!oe.isWindow(r)){c=r[a];c&&(r[a]=null);oe.event.triggered=d;try{r[d]()}catch(g){}oe.event.triggered=void 0;c&&(r[a]=c)}return t.result}}},dispatch:function(t){t=oe.event.fix(t);var e,n,r,i,o,a=[],s=J.call(arguments),l=(oe._data(this,"events")||{})[t.type]||[],u=oe.event.special[t.type]||{};s[0]=t;t.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,t)!==!1){a=oe.event.handlers.call(this,t,l);e=0;for(;(i=a[e++])&&!t.isPropagationStopped();){t.currentTarget=i.elem;o=0;for(;(r=i.handlers[o++])&&!t.isImmediatePropagationStopped();)if(!t.namespace_re||t.namespace_re.test(r.namespace)){t.handleObj=r;t.data=r.data;n=((oe.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s);if(void 0!==n&&(t.result=n)===!1){t.preventDefault();t.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,t);return t.result}},handlers:function(t,e){var n,r,i,o,a=[],s=e.delegateCount,l=t.target;if(s&&l.nodeType&&(!t.button||"click"!==t.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==t.type)){i=[];for(o=0;s>o;o++){r=e[o];n=r.selector+" ";void 0===i[n]&&(i[n]=r.needsContext?oe(n,this).index(l)>=0:oe.find(n,this,null,[l]).length);i[n]&&i.push(r)}i.length&&a.push({elem:l,handlers:i})}s<e.length&&a.push({elem:this,handlers:e.slice(s)});return a},fix:function(t){if(t[oe.expando])return t;var e,n,r,i=t.type,o=t,a=this.fixHooks[i];a||(this.fixHooks[i]=a=Ie.test(i)?this.mouseHooks:je.test(i)?this.keyHooks:{});r=a.props?this.props.concat(a.props):this.props;t=new oe.Event(o);e=r.length;for(;e--;){n=r[e];t[n]=o[n]}t.target||(t.target=o.srcElement||ge);3===t.target.nodeType&&(t.target=t.target.parentNode);t.metaKey=!!t.metaKey;return a.filter?a.filter(t,o):t},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(t,e){null==t.which&&(t.which=null!=e.charCode?e.charCode:e.keyCode);return t}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(t,e){var n,r,i,o=e.button,a=e.fromElement;if(null==t.pageX&&null!=e.clientX){r=t.target.ownerDocument||ge;i=r.documentElement;n=r.body;t.pageX=e.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0);t.pageY=e.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)}!t.relatedTarget&&a&&(t.relatedTarget=a===t.target?e.toElement:a);t.which||void 0===o||(t.which=1&o?1:2&o?3:4&o?2:0);return t}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==g()&&this.focus)try{this.focus();return!1}catch(t){}},delegateType:"focusin"},blur:{trigger:function(){if(this===g()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(oe.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(t){return oe.nodeName(t.target,"a")}},beforeunload:{postDispatch:function(t){void 0!==t.result&&t.originalEvent&&(t.originalEvent.returnValue=t.result)}}},simulate:function(t,e,n,r){var i=oe.extend(new oe.Event,n,{type:t,isSimulated:!0,originalEvent:{}});r?oe.event.trigger(i,null,e):oe.event.dispatch.call(e,i);i.isDefaultPrevented()&&n.preventDefault()}};oe.removeEvent=ge.removeEventListener?function(t,e,n){t.removeEventListener&&t.removeEventListener(e,n,!1)}:function(t,e,n){var r="on"+e;if(t.detachEvent){typeof t[r]===Te&&(t[r]=null);t.detachEvent(r,n)}};oe.Event=function(t,e){if(!(this instanceof oe.Event))return new oe.Event(t,e);if(t&&t.type){this.originalEvent=t;this.type=t.type;this.isDefaultPrevented=t.defaultPrevented||void 0===t.defaultPrevented&&t.returnValue===!1?d:p}else this.type=t;e&&oe.extend(this,e);this.timeStamp=t&&t.timeStamp||oe.now();this[oe.expando]=!0};oe.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var t=this.originalEvent;this.isDefaultPrevented=d;t&&(t.preventDefault?t.preventDefault():t.returnValue=!1)},stopPropagation:function(){var t=this.originalEvent;this.isPropagationStopped=d;if(t){t.stopPropagation&&t.stopPropagation();t.cancelBubble=!0}},stopImmediatePropagation:function(){var t=this.originalEvent;this.isImmediatePropagationStopped=d;t&&t.stopImmediatePropagation&&t.stopImmediatePropagation();this.stopPropagation()}};oe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(t,e){oe.event.special[t]={delegateType:e,bindType:e,handle:function(t){var n,r=this,i=t.relatedTarget,o=t.handleObj;if(!i||i!==r&&!oe.contains(r,i)){t.type=o.origType;n=o.handler.apply(this,arguments);t.type=e}return n}}});re.submitBubbles||(oe.event.special.submit={setup:function(){if(oe.nodeName(this,"form"))return!1;oe.event.add(this,"click._submit keypress._submit",function(t){var e=t.target,n=oe.nodeName(e,"input")||oe.nodeName(e,"button")?e.form:void 0;if(n&&!oe._data(n,"submitBubbles")){oe.event.add(n,"submit._submit",function(t){t._submit_bubble=!0});oe._data(n,"submitBubbles",!0)}});return void 0},postDispatch:function(t){if(t._submit_bubble){delete t._submit_bubble;this.parentNode&&!t.isTrigger&&oe.event.simulate("submit",this.parentNode,t,!0)}},teardown:function(){if(oe.nodeName(this,"form"))return!1;oe.event.remove(this,"._submit");return void 0}});re.changeBubbles||(oe.event.special.change={setup:function(){if(Ee.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){oe.event.add(this,"propertychange._change",function(t){"checked"===t.originalEvent.propertyName&&(this._just_changed=!0)});oe.event.add(this,"click._change",function(t){this._just_changed&&!t.isTrigger&&(this._just_changed=!1);oe.event.simulate("change",this,t,!0)})}return!1}oe.event.add(this,"beforeactivate._change",function(t){var e=t.target;if(Ee.test(e.nodeName)&&!oe._data(e,"changeBubbles")){oe.event.add(e,"change._change",function(t){!this.parentNode||t.isSimulated||t.isTrigger||oe.event.simulate("change",this.parentNode,t,!0)});oe._data(e,"changeBubbles",!0)}})},handle:function(t){var e=t.target;return this!==e||t.isSimulated||t.isTrigger||"radio"!==e.type&&"checkbox"!==e.type?t.handleObj.handler.apply(this,arguments):void 0},teardown:function(){oe.event.remove(this,"._change");return!Ee.test(this.nodeName)}});re.focusinBubbles||oe.each({focus:"focusin",blur:"focusout"},function(t,e){var n=function(t){oe.event.simulate(e,t.target,oe.event.fix(t),!0)};oe.event.special[e]={setup:function(){var r=this.ownerDocument||this,i=oe._data(r,e);i||r.addEventListener(t,n,!0);oe._data(r,e,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=oe._data(r,e)-1;if(i)oe._data(r,e,i);else{r.removeEventListener(t,n,!0);oe._removeData(r,e)}}}});oe.fn.extend({on:function(t,e,n,r,i){var o,a;if("object"==typeof t){if("string"!=typeof e){n=n||e;e=void 0}for(o in t)this.on(o,e,n,t[o],i);return this}if(null==n&&null==r){r=e;n=e=void 0}else if(null==r)if("string"==typeof e){r=n;n=void 0}else{r=n;n=e;e=void 0}if(r===!1)r=p;else if(!r)return this;if(1===i){a=r;r=function(t){oe().off(t);return a.apply(this,arguments)};r.guid=a.guid||(a.guid=oe.guid++)}return this.each(function(){oe.event.add(this,t,r,n,e)})},one:function(t,e,n,r){return this.on(t,e,n,r,1)},off:function(t,e,n){var r,i;if(t&&t.preventDefault&&t.handleObj){r=t.handleObj;oe(t.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof t){for(i in t)this.off(i,e,t[i]);return this}if(e===!1||"function"==typeof e){n=e;e=void 0}n===!1&&(n=p);return this.each(function(){oe.event.remove(this,t,n,e)})},trigger:function(t,e){return this.each(function(){oe.event.trigger(t,e,this)})},triggerHandler:function(t,e){var n=this[0];return n?oe.event.trigger(t,e,n,!0):void 0}});var Oe="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Fe=/ jQuery\d+="(?:null|\d+)"/g,Re=new RegExp("<(?:"+Oe+")[\\s/>]","i"),We=/^\s+/,ze=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,qe=/<([\w:]+)/,Ue=/<tbody/i,Be=/<|&#?\w+;/,Ve=/<(?:script|style|link)/i,Xe=/checked\s*(?:[^=]|=\s*.checked.)/i,Ge=/^$|\/(?:java|ecma)script/i,$e=/^true\/(.*)/,Ye=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Je={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:re.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Ke=m(ge),Ze=Ke.appendChild(ge.createElement("div"));Je.optgroup=Je.option;Je.tbody=Je.tfoot=Je.colgroup=Je.caption=Je.thead;Je.th=Je.td;oe.extend({clone:function(t,e,n){var r,i,o,a,s,l=oe.contains(t.ownerDocument,t);if(re.html5Clone||oe.isXMLDoc(t)||!Re.test("<"+t.nodeName+">"))o=t.cloneNode(!0);else{Ze.innerHTML=t.outerHTML;Ze.removeChild(o=Ze.firstChild)}if(!(re.noCloneEvent&&re.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||oe.isXMLDoc(t))){r=v(o);s=v(t);for(a=0;null!=(i=s[a]);++a)r[a]&&T(i,r[a])}if(e)if(n){s=s||v(t);r=r||v(o);for(a=0;null!=(i=s[a]);a++)S(i,r[a])}else S(t,o);r=v(o,"script");r.length>0&&C(r,!l&&v(t,"script"));r=s=i=null;return o},buildFragment:function(t,e,n,r){for(var i,o,a,s,l,u,c,f=t.length,h=m(e),d=[],p=0;f>p;p++){o=t[p];if(o||0===o)if("object"===oe.type(o))oe.merge(d,o.nodeType?[o]:o);else if(Be.test(o)){s=s||h.appendChild(e.createElement("div"));l=(qe.exec(o)||["",""])[1].toLowerCase();c=Je[l]||Je._default;s.innerHTML=c[1]+o.replace(ze,"<$1></$2>")+c[2];i=c[0];for(;i--;)s=s.lastChild;!re.leadingWhitespace&&We.test(o)&&d.push(e.createTextNode(We.exec(o)[0]));if(!re.tbody){o="table"!==l||Ue.test(o)?"<table>"!==c[1]||Ue.test(o)?0:s:s.firstChild;i=o&&o.childNodes.length;for(;i--;)oe.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}oe.merge(d,s.childNodes);s.textContent="";for(;s.firstChild;)s.removeChild(s.firstChild);s=h.lastChild}else d.push(e.createTextNode(o))}s&&h.removeChild(s);re.appendChecked||oe.grep(v(d,"input"),y);p=0;for(;o=d[p++];)if(!r||-1===oe.inArray(o,r)){a=oe.contains(o.ownerDocument,o);s=v(h.appendChild(o),"script");a&&C(s);if(n){i=0;for(;o=s[i++];)Ge.test(o.type||"")&&n.push(o)}}s=null;return h},cleanData:function(t,e){for(var n,r,i,o,a=0,s=oe.expando,l=oe.cache,u=re.deleteExpando,c=oe.event.special;null!=(n=t[a]);a++)if(e||oe.acceptData(n)){i=n[s];o=i&&l[i];if(o){if(o.events)for(r in o.events)c[r]?oe.event.remove(n,r):oe.removeEvent(n,r,o.handle);if(l[i]){delete l[i];u?delete n[s]:typeof n.removeAttribute!==Te?n.removeAttribute(s):n[s]=null;Y.push(i)}}}}});oe.fn.extend({text:function(t){return Ae(this,function(t){return void 0===t?oe.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ge).createTextNode(t))},null,t,arguments.length)},append:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=b(this,t);e.appendChild(t)}})},prepend:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=b(this,t);e.insertBefore(t,e.firstChild)}})},before:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this)})},after:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)})},remove:function(t,e){for(var n,r=t?oe.filter(t,this):this,i=0;null!=(n=r[i]);i++){e||1!==n.nodeType||oe.cleanData(v(n));if(n.parentNode){e&&oe.contains(n.ownerDocument,n)&&C(v(n,"script"));n.parentNode.removeChild(n)}}return this},empty:function(){for(var t,e=0;null!=(t=this[e]);e++){1===t.nodeType&&oe.cleanData(v(t,!1));for(;t.firstChild;)t.removeChild(t.firstChild);t.options&&oe.nodeName(t,"select")&&(t.options.length=0)}return this},clone:function(t,e){t=null==t?!1:t;e=null==e?t:e;return this.map(function(){return oe.clone(this,t,e)})},html:function(t){return Ae(this,function(t){var e=this[0]||{},n=0,r=this.length;if(void 0===t)return 1===e.nodeType?e.innerHTML.replace(Fe,""):void 0;if(!("string"!=typeof t||Ve.test(t)||!re.htmlSerialize&&Re.test(t)||!re.leadingWhitespace&&We.test(t)||Je[(qe.exec(t)||["",""])[1].toLowerCase()])){t=t.replace(ze,"<$1></$2>");try{for(;r>n;n++){e=this[n]||{};if(1===e.nodeType){oe.cleanData(v(e,!1));e.innerHTML=t}}e=0}catch(i){}}e&&this.empty().append(t)},null,t,arguments.length)},replaceWith:function(){var t=arguments[0];this.domManip(arguments,function(e){t=this.parentNode;oe.cleanData(v(this));t&&t.replaceChild(e,this)});return t&&(t.length||t.nodeType)?this:this.remove()},detach:function(t){return this.remove(t,!0)},domManip:function(t,e){t=K.apply([],t);var n,r,i,o,a,s,l=0,u=this.length,c=this,f=u-1,h=t[0],d=oe.isFunction(h);if(d||u>1&&"string"==typeof h&&!re.checkClone&&Xe.test(h))return this.each(function(n){var r=c.eq(n);d&&(t[0]=h.call(this,n,r.html()));r.domManip(t,e)});if(u){s=oe.buildFragment(t,this[0].ownerDocument,!1,this);n=s.firstChild;1===s.childNodes.length&&(s=n);if(n){o=oe.map(v(s,"script"),x);i=o.length;for(;u>l;l++){r=s;if(l!==f){r=oe.clone(r,!0,!0);i&&oe.merge(o,v(r,"script"))}e.call(this[l],r,l)}if(i){a=o[o.length-1].ownerDocument;oe.map(o,w);for(l=0;i>l;l++){r=o[l];Ge.test(r.type||"")&&!oe._data(r,"globalEval")&&oe.contains(a,r)&&(r.src?oe._evalUrl&&oe._evalUrl(r.src):oe.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Ye,"")))}}s=n=null}}return this}});oe.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(t,e){oe.fn[t]=function(t){for(var n,r=0,i=[],o=oe(t),a=o.length-1;a>=r;r++){n=r===a?this:this.clone(!0);oe(o[r])[e](n);Z.apply(i,n.get())}return this.pushStack(i)}});var Qe,tn={};(function(){var t;re.shrinkWrapBlocks=function(){if(null!=t)return t;t=!1;var e,n,r;n=ge.getElementsByTagName("body")[0];if(n&&n.style){e=ge.createElement("div");r=ge.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(e);if(typeof e.style.zoom!==Te){e.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";e.appendChild(ge.createElement("div")).style.width="5px";t=3!==e.offsetWidth}n.removeChild(r);return t}}})();var en,nn,rn=/^margin/,on=new RegExp("^("+Me+")(?!px)[a-z%]+$","i"),an=/^(top|right|bottom|left)$/;if(e.getComputedStyle){en=function(t){return t.ownerDocument.defaultView.getComputedStyle(t,null)};nn=function(t,e,n){var r,i,o,a,s=t.style;n=n||en(t);a=n?n.getPropertyValue(e)||n[e]:void 0;if(n){""!==a||oe.contains(t.ownerDocument,t)||(a=oe.style(t,e));if(on.test(a)&&rn.test(e)){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}}return void 0===a?a:a+""}}else if(ge.documentElement.currentStyle){en=function(t){return t.currentStyle};nn=function(t,e,n){var r,i,o,a,s=t.style;n=n||en(t);a=n?n[e]:void 0;null==a&&s&&s[e]&&(a=s[e]);if(on.test(a)&&!an.test(e)){r=s.left;i=t.runtimeStyle;o=i&&i.left;o&&(i.left=t.currentStyle.left);s.left="fontSize"===e?"1em":a;a=s.pixelLeft+"px";s.left=r;o&&(i.left=o)}return void 0===a?a:a+""||"auto"}}(function(){function t(){var t,n,r,i;n=ge.getElementsByTagName("body")[0];if(n&&n.style){t=ge.createElement("div");r=ge.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;if(e.getComputedStyle){o="1%"!==(e.getComputedStyle(t,null)||{}).top;a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width;i=t.appendChild(ge.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;if(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=ge.createElement("div");n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";i=n.getElementsByTagName("a")[0];r=i&&i.style;if(r){r.cssText="float:left;opacity:.5";re.opacity="0.5"===r.opacity;re.cssFloat=!!r.cssFloat;n.style.backgroundClip="content-box";n.cloneNode(!0).style.backgroundClip="";re.clearCloneStyle="content-box"===n.style.backgroundClip;re.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;oe.extend(re,{reliableHiddenOffsets:function(){null==s&&t();return s},boxSizingReliable:function(){null==a&&t();return a},pixelPosition:function(){null==o&&t();return o},reliableMarginRight:function(){null==l&&t();return l}})}})();oe.swap=function(t,e,n,r){var i,o,a={};for(o in e){a[o]=t.style[o];t.style[o]=e[o]}i=n.apply(t,r||[]);for(o in e)t.style[o]=a[o];return i};var sn=/alpha\([^)]*\)/i,ln=/opacity\s*=\s*([^)]*)/,un=/^(none|table(?!-c[ea]).+)/,cn=new RegExp("^("+Me+")(.*)$","i"),fn=new RegExp("^([+-])=("+Me+")","i"),hn={position:"absolute",visibility:"hidden",display:"block"},dn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];oe.extend({cssHooks:{opacity:{get:function(t,e){if(e){var n=nn(t,"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":re.cssFloat?"cssFloat":"styleFloat"},style:function(t,e,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var i,o,a,s=oe.camelCase(e),l=t.style;e=oe.cssProps[s]||(oe.cssProps[s]=D(l,s));a=oe.cssHooks[e]||oe.cssHooks[s];if(void 0===n)return a&&"get"in a&&void 0!==(i=a.get(t,!1,r))?i:l[e];o=typeof n;if("string"===o&&(i=fn.exec(n))){n=(i[1]+1)*i[2]+parseFloat(oe.css(t,e));o="number"}if(null!=n&&n===n){"number"!==o||oe.cssNumber[s]||(n+="px");re.clearCloneStyle||""!==n||0!==e.indexOf("background")||(l[e]="inherit");if(!(a&&"set"in a&&void 0===(n=a.set(t,n,r))))try{l[e]=n}catch(u){}}}},css:function(t,e,n,r){var i,o,a,s=oe.camelCase(e);e=oe.cssProps[s]||(oe.cssProps[s]=D(t.style,s));a=oe.cssHooks[e]||oe.cssHooks[s];a&&"get"in a&&(o=a.get(t,!0,n));void 0===o&&(o=nn(t,e,r));"normal"===o&&e in dn&&(o=dn[e]);if(""===n||n){i=parseFloat(o);return n===!0||oe.isNumeric(i)?i||0:o}return o}});oe.each(["height","width"],function(t,e){oe.cssHooks[e]={get:function(t,n,r){return n?un.test(oe.css(t,"display"))&&0===t.offsetWidth?oe.swap(t,hn,function(){return E(t,e,r)}):E(t,e,r):void 0},set:function(t,n,r){var i=r&&en(t);return A(t,n,r?N(t,e,r,re.boxSizing&&"border-box"===oe.css(t,"boxSizing",!1,i),i):0)}}});re.opacity||(oe.cssHooks.opacity={get:function(t,e){return ln.test((e&&t.currentStyle?t.currentStyle.filter:t.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":e?"1":""},set:function(t,e){var n=t.style,r=t.currentStyle,i=oe.isNumeric(e)?"alpha(opacity="+100*e+")":"",o=r&&r.filter||n.filter||"";n.zoom=1;if((e>=1||""===e)&&""===oe.trim(o.replace(sn,""))&&n.removeAttribute){n.removeAttribute("filter");if(""===e||r&&!r.filter)return}n.filter=sn.test(o)?o.replace(sn,i):o+" "+i}});oe.cssHooks.marginRight=M(re.reliableMarginRight,function(t,e){return e?oe.swap(t,{display:"inline-block"},nn,[t,"marginRight"]):void 0});oe.each({margin:"",padding:"",border:"Width"},function(t,e){oe.cssHooks[t+e]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[t+De[r]+e]=o[r]||o[r-2]||o[0];return i}};rn.test(t)||(oe.cssHooks[t+e].set=A)});oe.fn.extend({css:function(t,e){return Ae(this,function(t,e,n){var r,i,o={},a=0;if(oe.isArray(e)){r=en(t);i=e.length;for(;i>a;a++)o[e[a]]=oe.css(t,e[a],!1,r);return o}return void 0!==n?oe.style(t,e,n):oe.css(t,e)},t,e,arguments.length>1)},show:function(){return L(this,!0)},hide:function(){return L(this)},toggle:function(t){return"boolean"==typeof t?t?this.show():this.hide():this.each(function(){Le(this)?oe(this).show():oe(this).hide()})}});oe.Tween=j;j.prototype={constructor:j,init:function(t,e,n,r,i,o){this.elem=t;this.prop=n;this.easing=i||"swing";this.options=e;this.start=this.now=this.cur();this.end=r;this.unit=o||(oe.cssNumber[n]?"":"px")},cur:function(){var t=j.propHooks[this.prop];return t&&t.get?t.get(this):j.propHooks._default.get(this)},run:function(t){var e,n=j.propHooks[this.prop];this.pos=e=this.options.duration?oe.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):t;this.now=(this.end-this.start)*e+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);n&&n.set?n.set(this):j.propHooks._default.set(this);return this}};j.prototype.init.prototype=j.prototype;j.propHooks={_default:{get:function(t){var e;if(null!=t.elem[t.prop]&&(!t.elem.style||null==t.elem.style[t.prop]))return t.elem[t.prop];e=oe.css(t.elem,t.prop,"");return e&&"auto"!==e?e:0},set:function(t){oe.fx.step[t.prop]?oe.fx.step[t.prop](t):t.elem.style&&(null!=t.elem.style[oe.cssProps[t.prop]]||oe.cssHooks[t.prop])?oe.style(t.elem,t.prop,t.now+t.unit):t.elem[t.prop]=t.now}}};j.propHooks.scrollTop=j.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}};oe.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2}};oe.fx=j.prototype.init;oe.fx.step={};var gn,mn,vn=/^(?:toggle|show|hide)$/,yn=new RegExp("^(?:([+-])=|)("+Me+")([a-z%]*)$","i"),bn=/queueHooks$/,xn=[O],wn={"*":[function(t,e){var n=this.createTween(t,e),r=n.cur(),i=yn.exec(e),o=i&&i[3]||(oe.cssNumber[t]?"":"px"),a=(oe.cssNumber[t]||"px"!==o&&+r)&&yn.exec(oe.css(n.elem,t)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3];i=i||[];a=+r||1;do{s=s||".5";a/=s;oe.style(n.elem,t,a+o)}while(s!==(s=n.cur()/r)&&1!==s&&--l)}if(i){a=n.start=+a||+r||0;n.unit=o;n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]}return n}]};oe.Animation=oe.extend(R,{tweener:function(t,e){if(oe.isFunction(t)){e=t;t=["*"]}else t=t.split(" ");for(var n,r=0,i=t.length;i>r;r++){n=t[r];wn[n]=wn[n]||[];wn[n].unshift(e)}},prefilter:function(t,e){e?xn.unshift(t):xn.push(t)}});oe.speed=function(t,e,n){var r=t&&"object"==typeof t?oe.extend({},t):{complete:n||!n&&e||oe.isFunction(t)&&t,duration:t,easing:n&&e||e&&!oe.isFunction(e)&&e};r.duration=oe.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in oe.fx.speeds?oe.fx.speeds[r.duration]:oe.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){oe.isFunction(r.old)&&r.old.call(this);r.queue&&oe.dequeue(this,r.queue)};return r};oe.fn.extend({fadeTo:function(t,e,n,r){return this.filter(Le).css("opacity",0).show().end().animate({opacity:e},t,n,r)},animate:function(t,e,n,r){var i=oe.isEmptyObject(t),o=oe.speed(e,n,r),a=function(){var e=R(this,oe.extend({},t),o);(i||oe._data(this,"finish"))&&e.stop(!0)};a.finish=a;return i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(t,e,n){var r=function(t){var e=t.stop;delete t.stop;e(n)};if("string"!=typeof t){n=e;e=t;t=void 0}e&&t!==!1&&this.queue(t||"fx",[]);return this.each(function(){var e=!0,i=null!=t&&t+"queueHooks",o=oe.timers,a=oe._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&bn.test(i)&&r(a[i]);for(i=o.length;i--;)if(o[i].elem===this&&(null==t||o[i].queue===t)){o[i].anim.stop(n);e=!1;o.splice(i,1)}(e||!n)&&oe.dequeue(this,t)})},finish:function(t){t!==!1&&(t=t||"fx");return this.each(function(){var e,n=oe._data(this),r=n[t+"queue"],i=n[t+"queueHooks"],o=oe.timers,a=r?r.length:0;n.finish=!0;oe.queue(this,t,[]);i&&i.stop&&i.stop.call(this,!0);for(e=o.length;e--;)if(o[e].elem===this&&o[e].queue===t){o[e].anim.stop(!0);o.splice(e,1)}for(e=0;a>e;e++)r[e]&&r[e].finish&&r[e].finish.call(this);delete n.finish})}});oe.each(["toggle","show","hide"],function(t,e){var n=oe.fn[e];oe.fn[e]=function(t,r,i){return null==t||"boolean"==typeof t?n.apply(this,arguments):this.animate(P(e,!0),t,r,i)}});oe.each({slideDown:P("show"),slideUp:P("hide"),slideToggle:P("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(t,e){oe.fn[t]=function(t,n,r){return this.animate(e,t,n,r)}});oe.timers=[];oe.fx.tick=function(){var t,e=oe.timers,n=0;gn=oe.now();for(;n<e.length;n++){t=e[n];t()||e[n]!==t||e.splice(n--,1)}e.length||oe.fx.stop();gn=void 0};oe.fx.timer=function(t){oe.timers.push(t);t()?oe.fx.start():oe.timers.pop()};oe.fx.interval=13;oe.fx.start=function(){mn||(mn=setInterval(oe.fx.tick,oe.fx.interval))};oe.fx.stop=function(){clearInterval(mn);mn=null};oe.fx.speeds={slow:600,fast:200,_default:400};oe.fn.delay=function(t,e){t=oe.fx?oe.fx.speeds[t]||t:t;e=e||"fx";return this.queue(e,function(e,n){var r=setTimeout(e,t);n.stop=function(){clearTimeout(r)}})};(function(){var t,e,n,r,i;e=ge.createElement("div");e.setAttribute("className","t");e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=e.getElementsByTagName("a")[0];n=ge.createElement("select");i=n.appendChild(ge.createElement("option"));t=e.getElementsByTagName("input")[0];r.style.cssText="top:1px";re.getSetAttribute="t"!==e.className;re.style=/top/.test(r.getAttribute("style"));re.hrefNormalized="/a"===r.getAttribute("href");re.checkOn=!!t.value;re.optSelected=i.selected;re.enctype=!!ge.createElement("form").enctype;n.disabled=!0;re.optDisabled=!i.disabled;t=ge.createElement("input");t.setAttribute("value","");re.input=""===t.getAttribute("value");t.value="t";t.setAttribute("type","radio");re.radioValue="t"===t.value})();var Cn=/\r/g;oe.fn.extend({val:function(t){var e,n,r,i=this[0];if(arguments.length){r=oe.isFunction(t);return this.each(function(n){var i;if(1===this.nodeType){i=r?t.call(this,n,oe(this).val()):t;null==i?i="":"number"==typeof i?i+="":oe.isArray(i)&&(i=oe.map(i,function(t){return null==t?"":t+""}));e=oe.valHooks[this.type]||oe.valHooks[this.nodeName.toLowerCase()];e&&"set"in e&&void 0!==e.set(this,i,"value")||(this.value=i)}})}if(i){e=oe.valHooks[i.type]||oe.valHooks[i.nodeName.toLowerCase()];if(e&&"get"in e&&void 0!==(n=e.get(i,"value")))return n;n=i.value;return"string"==typeof n?n.replace(Cn,""):null==n?"":n}}});oe.extend({valHooks:{option:{get:function(t){var e=oe.find.attr(t,"value");return null!=e?e:oe.trim(oe.text(t))}},select:{get:function(t){for(var e,n,r=t.options,i=t.selectedIndex,o="select-one"===t.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++){n=r[l];if(!(!n.selected&&l!==i||(re.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&oe.nodeName(n.parentNode,"optgroup"))){e=oe(n).val();if(o)return e;a.push(e)}}return a},set:function(t,e){for(var n,r,i=t.options,o=oe.makeArray(e),a=i.length;a--;){r=i[a];if(oe.inArray(oe.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1}n||(t.selectedIndex=-1);return i}}}});oe.each(["radio","checkbox"],function(){oe.valHooks[this]={set:function(t,e){return oe.isArray(e)?t.checked=oe.inArray(oe(t).val(),e)>=0:void 0}};re.checkOn||(oe.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})});var Sn,Tn,kn=oe.expr.attrHandle,_n=/^(?:checked|selected)$/i,Mn=re.getSetAttribute,Dn=re.input;oe.fn.extend({attr:function(t,e){return Ae(this,oe.attr,t,e,arguments.length>1)},removeAttr:function(t){return this.each(function(){oe.removeAttr(this,t)})}});oe.extend({attr:function(t,e,n){var r,i,o=t.nodeType;if(t&&3!==o&&8!==o&&2!==o){if(typeof t.getAttribute===Te)return oe.prop(t,e,n);if(1!==o||!oe.isXMLDoc(t)){e=e.toLowerCase();r=oe.attrHooks[e]||(oe.expr.match.bool.test(e)?Tn:Sn)}if(void 0===n){if(r&&"get"in r&&null!==(i=r.get(t,e)))return i;i=oe.find.attr(t,e);return null==i?void 0:i}if(null!==n){if(r&&"set"in r&&void 0!==(i=r.set(t,n,e)))return i;t.setAttribute(e,n+"");return n}oe.removeAttr(t,e)}},removeAttr:function(t,e){var n,r,i=0,o=e&&e.match(xe);if(o&&1===t.nodeType)for(;n=o[i++];){r=oe.propFix[n]||n;oe.expr.match.bool.test(n)?Dn&&Mn||!_n.test(n)?t[r]=!1:t[oe.camelCase("default-"+n)]=t[r]=!1:oe.attr(t,n,"");t.removeAttribute(Mn?n:r)}},attrHooks:{type:{set:function(t,e){if(!re.radioValue&&"radio"===e&&oe.nodeName(t,"input")){var n=t.value;t.setAttribute("type",e);n&&(t.value=n);return e}}}}});Tn={set:function(t,e,n){e===!1?oe.removeAttr(t,n):Dn&&Mn||!_n.test(n)?t.setAttribute(!Mn&&oe.propFix[n]||n,n):t[oe.camelCase("default-"+n)]=t[n]=!0;return n}};oe.each(oe.expr.match.bool.source.match(/\w+/g),function(t,e){var n=kn[e]||oe.find.attr;kn[e]=Dn&&Mn||!_n.test(e)?function(t,e,r){var i,o;if(!r){o=kn[e];kn[e]=i;i=null!=n(t,e,r)?e.toLowerCase():null;kn[e]=o}return i}:function(t,e,n){return n?void 0:t[oe.camelCase("default-"+e)]?e.toLowerCase():null}});Dn&&Mn||(oe.attrHooks.value={set:function(t,e,n){if(!oe.nodeName(t,"input"))return Sn&&Sn.set(t,e,n);t.defaultValue=e;return void 0}});if(!Mn){Sn={set:function(t,e,n){var r=t.getAttributeNode(n);r||t.setAttributeNode(r=t.ownerDocument.createAttribute(n));r.value=e+="";return"value"===n||e===t.getAttribute(n)?e:void 0}};kn.id=kn.name=kn.coords=function(t,e,n){var r;return n?void 0:(r=t.getAttributeNode(e))&&""!==r.value?r.value:null};oe.valHooks.button={get:function(t,e){var n=t.getAttributeNode(e);return n&&n.specified?n.value:void 0},set:Sn.set};oe.attrHooks.contenteditable={set:function(t,e,n){Sn.set(t,""===e?!1:e,n)}};oe.each(["width","height"],function(t,e){oe.attrHooks[e]={set:function(t,n){if(""===n){t.setAttribute(e,"auto");return n}}}})}re.style||(oe.attrHooks.style={get:function(t){return t.style.cssText||void 0},set:function(t,e){return t.style.cssText=e+""}});var Ln=/^(?:input|select|textarea|button|object)$/i,An=/^(?:a|area)$/i;oe.fn.extend({prop:function(t,e){return Ae(this,oe.prop,t,e,arguments.length>1)},removeProp:function(t){t=oe.propFix[t]||t;return this.each(function(){try{this[t]=void 0;delete this[t]}catch(e){}})}});oe.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(t,e,n){var r,i,o,a=t.nodeType;if(t&&3!==a&&8!==a&&2!==a){o=1!==a||!oe.isXMLDoc(t);if(o){e=oe.propFix[e]||e;i=oe.propHooks[e]}return void 0!==n?i&&"set"in i&&void 0!==(r=i.set(t,n,e))?r:t[e]=n:i&&"get"in i&&null!==(r=i.get(t,e))?r:t[e]}},propHooks:{tabIndex:{get:function(t){var e=oe.find.attr(t,"tabindex");return e?parseInt(e,10):Ln.test(t.nodeName)||An.test(t.nodeName)&&t.href?0:-1}}}});re.hrefNormalized||oe.each(["href","src"],function(t,e){oe.propHooks[e]={get:function(t){return t.getAttribute(e,4)}}});re.optSelected||(oe.propHooks.selected={get:function(t){var e=t.parentNode;if(e){e.selectedIndex;e.parentNode&&e.parentNode.selectedIndex}return null}});oe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){oe.propFix[this.toLowerCase()]=this});re.enctype||(oe.propFix.enctype="encoding");var Nn=/[\t\r\n\f]/g;oe.fn.extend({addClass:function(t){var e,n,r,i,o,a,s=0,l=this.length,u="string"==typeof t&&t;if(oe.isFunction(t))return this.each(function(e){oe(this).addClass(t.call(this,e,this.className))});if(u){e=(t||"").match(xe)||[];for(;l>s;s++){n=this[s];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Nn," "):" ");if(r){o=0;for(;i=e[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=oe.trim(r);n.className!==a&&(n.className=a)}}}return this},removeClass:function(t){var e,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof t&&t;if(oe.isFunction(t))return this.each(function(e){oe(this).removeClass(t.call(this,e,this.className))});if(u){e=(t||"").match(xe)||[];for(;l>s;s++){n=this[s];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Nn," "):"");if(r){o=0;for(;i=e[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=t?oe.trim(r):"";n.className!==a&&(n.className=a)}}}return this},toggleClass:function(t,e){var n=typeof t;return"boolean"==typeof e&&"string"===n?e?this.addClass(t):this.removeClass(t):this.each(oe.isFunction(t)?function(n){oe(this).toggleClass(t.call(this,n,this.className,e),e)}:function(){if("string"===n)for(var e,r=0,i=oe(this),o=t.match(xe)||[];e=o[r++];)i.hasClass(e)?i.removeClass(e):i.addClass(e);else if(n===Te||"boolean"===n){this.className&&oe._data(this,"__className__",this.className);this.className=this.className||t===!1?"":oe._data(this,"__className__")||""}})},hasClass:function(t){for(var e=" "+t+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Nn," ").indexOf(e)>=0)return!0;return!1}});oe.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(t,e){oe.fn[e]=function(t,n){return arguments.length>0?this.on(e,null,t,n):this.trigger(e)}});oe.fn.extend({hover:function(t,e){return this.mouseenter(t).mouseleave(e||t)},bind:function(t,e,n){return this.on(t,null,e,n)},unbind:function(t,e){return this.off(t,null,e)},delegate:function(t,e,n,r){return this.on(e,t,n,r)},undelegate:function(t,e,n){return 1===arguments.length?this.off(t,"**"):this.off(e,t||"**",n)}});var En=oe.now(),jn=/\?/,In=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;oe.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=oe.trim(t+"");return i&&!oe.trim(i.replace(In,function(t,e,i,o){n&&e&&(r=0);if(0===r)return t;n=i||e;r+=!o-!i;return""}))?Function("return "+i)():oe.error("Invalid JSON: "+t)};oe.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{if(e.DOMParser){r=new DOMParser;n=r.parseFromString(t,"text/xml")}else{n=new ActiveXObject("Microsoft.XMLDOM");n.async="false";n.loadXML(t)}}catch(i){n=void 0}n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||oe.error("Invalid XML: "+t);return n};var Pn,Hn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Rn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Wn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,zn=/^(?:GET|HEAD)$/,qn=/^\/\//,Un=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Bn={},Vn={},Xn="*/".concat("*");try{Hn=location.href}catch(Gn){Hn=ge.createElement("a");Hn.href="";Hn=Hn.href}Pn=Un.exec(Hn.toLowerCase())||[];oe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Hn,type:"GET",isLocal:Wn.test(Pn[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":oe.parseJSON,"text xml":oe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?q(q(t,oe.ajaxSettings),e):q(oe.ajaxSettings,t)},ajaxPrefilter:W(Bn),ajaxTransport:W(Vn),ajax:function(t,e){function n(t,e,n,r){var i,c,v,y,x,C=e;if(2!==b){b=2;s&&clearTimeout(s);u=void 0;a=r||"";w.readyState=t>0?4:0;i=t>=200&&300>t||304===t;n&&(y=U(f,w,n));y=B(f,y,w,i);if(i){if(f.ifModified){x=w.getResponseHeader("Last-Modified");x&&(oe.lastModified[o]=x);x=w.getResponseHeader("etag");x&&(oe.etag[o]=x)}if(204===t||"HEAD"===f.type)C="nocontent";else if(304===t)C="notmodified";else{C=y.state;c=y.data;v=y.error;i=!v}}else{v=C;if(t||!C){C="error";0>t&&(t=0)}}w.status=t;w.statusText=(e||C)+"";i?p.resolveWith(h,[c,C,w]):p.rejectWith(h,[w,C,v]);w.statusCode(m);m=void 0;l&&d.trigger(i?"ajaxSuccess":"ajaxError",[w,f,i?c:v]);g.fireWith(h,[w,C]);if(l){d.trigger("ajaxComplete",[w,f]);--oe.active||oe.event.trigger("ajaxStop")}}}if("object"==typeof t){e=t;t=void 0}e=e||{};var r,i,o,a,s,l,u,c,f=oe.ajaxSetup({},e),h=f.context||f,d=f.context&&(h.nodeType||h.jquery)?oe(h):oe.event,p=oe.Deferred(),g=oe.Callbacks("once memory"),m=f.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(t){var e;if(2===b){if(!c){c={};for(;e=Rn.exec(a);)c[e[1].toLowerCase()]=e[2]}e=c[t.toLowerCase()]}return null==e?null:e},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(t,e){var n=t.toLowerCase();if(!b){t=y[n]=y[n]||t;v[t]=e}return this},overrideMimeType:function(t){b||(f.mimeType=t);return this},statusCode:function(t){var e;if(t)if(2>b)for(e in t)m[e]=[m[e],t[e]];else w.always(t[w.status]);return this},abort:function(t){var e=t||x;u&&u.abort(e);n(0,e);return this}};p.promise(w).complete=g.add;w.success=w.done;w.error=w.fail;f.url=((t||f.url||Hn)+"").replace(On,"").replace(qn,Pn[1]+"//");f.type=e.method||e.type||f.method||f.type;f.dataTypes=oe.trim(f.dataType||"*").toLowerCase().match(xe)||[""];if(null==f.crossDomain){r=Un.exec(f.url.toLowerCase());f.crossDomain=!(!r||r[1]===Pn[1]&&r[2]===Pn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Pn[3]||("http:"===Pn[1]?"80":"443")))}f.data&&f.processData&&"string"!=typeof f.data&&(f.data=oe.param(f.data,f.traditional));z(Bn,f,e,w);if(2===b)return w;l=f.global;l&&0===oe.active++&&oe.event.trigger("ajaxStart");f.type=f.type.toUpperCase();f.hasContent=!zn.test(f.type);o=f.url;if(!f.hasContent){if(f.data){o=f.url+=(jn.test(o)?"&":"?")+f.data;delete f.data}f.cache===!1&&(f.url=Fn.test(o)?o.replace(Fn,"$1_="+En++):o+(jn.test(o)?"&":"?")+"_="+En++)}if(f.ifModified){oe.lastModified[o]&&w.setRequestHeader("If-Modified-Since",oe.lastModified[o]);oe.etag[o]&&w.setRequestHeader("If-None-Match",oe.etag[o])}(f.data&&f.hasContent&&f.contentType!==!1||e.contentType)&&w.setRequestHeader("Content-Type",f.contentType);w.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Xn+"; q=0.01":""):f.accepts["*"]);for(i in f.headers)w.setRequestHeader(i,f.headers[i]);if(f.beforeSend&&(f.beforeSend.call(h,w,f)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](f[i]);u=z(Vn,f,e,w);if(u){w.readyState=1;l&&d.trigger("ajaxSend",[w,f]);f.async&&f.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},f.timeout));try{b=1;u.send(v,n)}catch(C){if(!(2>b))throw C;n(-1,C)}}else n(-1,"No Transport");return w},getJSON:function(t,e,n){return oe.get(t,e,n,"json")},getScript:function(t,e){return oe.get(t,void 0,e,"script")}});oe.each(["get","post"],function(t,e){oe[e]=function(t,n,r,i){if(oe.isFunction(n)){i=i||r;r=n;n=void 0}return oe.ajax({url:t,type:e,dataType:i,data:n,success:r})}});oe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(t,e){oe.fn[e]=function(t){return this.on(e,t)}});oe._evalUrl=function(t){return oe.ajax({url:t,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};oe.fn.extend({wrapAll:function(t){if(oe.isFunction(t))return this.each(function(e){oe(this).wrapAll(t.call(this,e))});if(this[0]){var e=oe(t,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&e.insertBefore(this[0]);e.map(function(){for(var t=this;t.firstChild&&1===t.firstChild.nodeType;)t=t.firstChild;return t}).append(this)}return this},wrapInner:function(t){return this.each(oe.isFunction(t)?function(e){oe(this).wrapInner(t.call(this,e))}:function(){var e=oe(this),n=e.contents();n.length?n.wrapAll(t):e.append(t)})},wrap:function(t){var e=oe.isFunction(t);return this.each(function(n){oe(this).wrapAll(e?t.call(this,n):t)})},unwrap:function(){return this.parent().each(function(){oe.nodeName(this,"body")||oe(this).replaceWith(this.childNodes)}).end()}});oe.expr.filters.hidden=function(t){return t.offsetWidth<=0&&t.offsetHeight<=0||!re.reliableHiddenOffsets()&&"none"===(t.style&&t.style.display||oe.css(t,"display"))};oe.expr.filters.visible=function(t){return!oe.expr.filters.hidden(t)};var $n=/%20/g,Yn=/\[\]$/,Jn=/\r?\n/g,Kn=/^(?:submit|button|image|reset|file)$/i,Zn=/^(?:input|select|textarea|keygen)/i;oe.param=function(t,e){var n,r=[],i=function(t,e){e=oe.isFunction(e)?e():null==e?"":e;r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(e)};void 0===e&&(e=oe.ajaxSettings&&oe.ajaxSettings.traditional);if(oe.isArray(t)||t.jquery&&!oe.isPlainObject(t))oe.each(t,function(){i(this.name,this.value)});else for(n in t)V(n,t[n],e,i);return r.join("&").replace($n,"+")};oe.fn.extend({serialize:function(){return oe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var t=oe.prop(this,"elements");return t?oe.makeArray(t):this}).filter(function(){var t=this.type;return this.name&&!oe(this).is(":disabled")&&Zn.test(this.nodeName)&&!Kn.test(t)&&(this.checked||!Ne.test(t))}).map(function(t,e){var n=oe(this).val();return null==n?null:oe.isArray(n)?oe.map(n,function(t){return{name:e.name,value:t.replace(Jn,"\r\n")}}):{name:e.name,value:n.replace(Jn,"\r\n")}}).get()}});oe.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||G()}:X;var Qn=0,tr={},er=oe.ajaxSettings.xhr();e.ActiveXObject&&oe(e).on("unload",function(){for(var t in tr)tr[t](void 0,!0)});re.cors=!!er&&"withCredentials"in er;er=re.ajax=!!er;er&&oe.ajaxTransport(function(t){if(!t.crossDomain||re.cors){var e;return{send:function(n,r){var i,o=t.xhr(),a=++Qn;o.open(t.type,t.url,t.async,t.username,t.password);if(t.xhrFields)for(i in t.xhrFields)o[i]=t.xhrFields[i];t.mimeType&&o.overrideMimeType&&o.overrideMimeType(t.mimeType);t.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(t.hasContent&&t.data||null);e=function(n,i){var s,l,u;if(e&&(i||4===o.readyState)){delete tr[a];e=void 0;o.onreadystatechange=oe.noop;if(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||!t.isLocal||t.crossDomain?1223===s&&(s=204):s=u.text?200:404}}u&&r(s,l,u,o.getAllResponseHeaders())};t.async?4===o.readyState?setTimeout(e):o.onreadystatechange=tr[a]=e:e()},abort:function(){e&&e(void 0,!0)}}}});oe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(t){oe.globalEval(t);return t}}});oe.ajaxPrefilter("script",function(t){void 0===t.cache&&(t.cache=!1);if(t.crossDomain){t.type="GET";t.global=!1}});oe.ajaxTransport("script",function(t){if(t.crossDomain){var e,n=ge.head||oe("head")[0]||ge.documentElement;return{send:function(r,i){e=ge.createElement("script");e.async=!0;t.scriptCharset&&(e.charset=t.scriptCharset);e.src=t.url;e.onload=e.onreadystatechange=function(t,n){if(n||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;e.parentNode&&e.parentNode.removeChild(e);e=null;n||i(200,"success")}};n.insertBefore(e,n.firstChild)},abort:function(){e&&e.onload(void 0,!0)}}}});var nr=[],rr=/(=)\?(?=&|$)|\?\?/;oe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var t=nr.pop()||oe.expando+"_"+En++;this[t]=!0;return t}});oe.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(rr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&rr.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0]){i=t.jsonpCallback=oe.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback;s?t[s]=t[s].replace(rr,"$1"+i):t.jsonp!==!1&&(t.url+=(jn.test(t.url)?"&":"?")+t.jsonp+"="+i);t.converters["script json"]=function(){a||oe.error(i+" was not called");return a[0]};t.dataTypes[0]="json";o=e[i];e[i]=function(){a=arguments};r.always(function(){e[i]=o;if(t[i]){t.jsonpCallback=n.jsonpCallback;nr.push(i)}a&&oe.isFunction(o)&&o(a[0]);a=o=void 0});return"script"}});oe.parseHTML=function(t,e,n){if(!t||"string"!=typeof t)return null;if("boolean"==typeof e){n=e;e=!1}e=e||ge;var r=he.exec(t),i=!n&&[];if(r)return[e.createElement(r[1])];r=oe.buildFragment([t],e,i);i&&i.length&&oe(i).remove();return oe.merge([],r.childNodes)};var ir=oe.fn.load;oe.fn.load=function(t,e,n){if("string"!=typeof t&&ir)return ir.apply(this,arguments);var r,i,o,a=this,s=t.indexOf(" ");if(s>=0){r=oe.trim(t.slice(s,t.length));t=t.slice(0,s)}if(oe.isFunction(e)){n=e;e=void 0}else e&&"object"==typeof e&&(o="POST");a.length>0&&oe.ajax({url:t,type:o,dataType:"html",data:e}).done(function(t){i=arguments;a.html(r?oe("<div>").append(oe.parseHTML(t)).find(r):t)}).complete(n&&function(t,e){a.each(n,i||[t.responseText,e,t])});return this};oe.expr.filters.animated=function(t){return oe.grep(oe.timers,function(e){return t===e.elem}).length};var or=e.document.documentElement;oe.offset={setOffset:function(t,e,n){var r,i,o,a,s,l,u,c=oe.css(t,"position"),f=oe(t),h={};"static"===c&&(t.style.position="relative");s=f.offset();o=oe.css(t,"top");l=oe.css(t,"left");u=("absolute"===c||"fixed"===c)&&oe.inArray("auto",[o,l])>-1;if(u){r=f.position();a=r.top;i=r.left}else{a=parseFloat(o)||0;i=parseFloat(l)||0}oe.isFunction(e)&&(e=e.call(t,n,s));null!=e.top&&(h.top=e.top-s.top+a);null!=e.left&&(h.left=e.left-s.left+i);"using"in e?e.using.call(t,h):f.css(h)}};oe.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){oe.offset.setOffset(this,t,e)});var e,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o){e=o.documentElement;if(!oe.contains(e,i))return r;typeof i.getBoundingClientRect!==Te&&(r=i.getBoundingClientRect());n=$(o);return{top:r.top+(n.pageYOffset||e.scrollTop)-(e.clientTop||0),left:r.left+(n.pageXOffset||e.scrollLeft)-(e.clientLeft||0)}}},position:function(){if(this[0]){var t,e,n={top:0,left:0},r=this[0];if("fixed"===oe.css(r,"position"))e=r.getBoundingClientRect();else{t=this.offsetParent();e=this.offset();oe.nodeName(t[0],"html")||(n=t.offset());n.top+=oe.css(t[0],"borderTopWidth",!0);n.left+=oe.css(t[0],"borderLeftWidth",!0)}return{top:e.top-n.top-oe.css(r,"marginTop",!0),left:e.left-n.left-oe.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||or;t&&!oe.nodeName(t,"html")&&"static"===oe.css(t,"position");)t=t.offsetParent;return t||or})}});oe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,e){var n=/Y/.test(e);oe.fn[t]=function(r){return Ae(this,function(t,r,i){var o=$(t);if(void 0===i)return o?e in o?o[e]:o.document.documentElement[r]:t[r];o?o.scrollTo(n?oe(o).scrollLeft():i,n?i:oe(o).scrollTop()):t[r]=i;return void 0},t,r,arguments.length,null)}});oe.each(["top","left"],function(t,e){oe.cssHooks[e]=M(re.pixelPosition,function(t,n){if(n){n=nn(t,e);return on.test(n)?oe(t).position()[e]+"px":n}})});oe.each({Height:"height",Width:"width"},function(t,e){oe.each({padding:"inner"+t,content:e,"":"outer"+t},function(n,r){oe.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Ae(this,function(e,n,r){var i;if(oe.isWindow(e))return e.document.documentElement["client"+t];if(9===e.nodeType){i=e.documentElement;return Math.max(e.body["scroll"+t],i["scroll"+t],e.body["offset"+t],i["offset"+t],i["client"+t])}return void 0===r?oe.css(e,n,a):oe.style(e,n,r,a)},e,o?r:void 0,o,null)}})});oe.fn.size=function(){return this.length};oe.fn.andSelf=oe.fn.addBack;"function"==typeof t&&t.amd&&t("jquery",[],function(){return oe});var ar=e.jQuery,sr=e.$;oe.noConflict=function(t){e.$===oe&&(e.$=sr);t&&e.jQuery===oe&&(e.jQuery=ar);return oe};typeof n===Te&&(e.jQuery=e.$=oe);return oe})},{}],19:[function(e,n,r){(function(){(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e;e=t;return e.pivotUtilities.d3_renderers={Treemap:function(t,n){var r,i,o,a,s,l,u,c,f,h,d,p,g,m;o={localeStrings:{}};n=e.extend(o,n);l=e("<div style='width: 100%; height: 100%;'>");c={name:"All",children:[]};r=function(t,e,n){var i,o,a,s,l,u,c;if(0!==e.length){null==(u=t.children)&&(t.children=[]); a=e.shift();c=t.children;for(s=0,l=c.length;l>s;s++){i=c[s];if(i.name===a){r(i,e,n);return}}o={name:a};r(o,e,n);return t.children.push(o)}t.value=n};m=t.getRowKeys();for(p=0,g=m.length;g>p;p++){u=m[p];h=t.getAggregator(u,[]).value();null!=h&&r(c,u,h)}i=d3.scale.category10();d=e(window).width()/1.4;a=e(window).height()/1.4;s=10;f=d3.layout.treemap().size([d,a]).sticky(!0).value(function(t){return t.size});d3.select(l[0]).append("div").style("position","relative").style("width",d+2*s+"px").style("height",a+2*s+"px").style("left",s+"px").style("top",s+"px").datum(c).selectAll(".node").data(f.padding([15,0,0,0]).value(function(t){return t.value}).nodes).enter().append("div").attr("class","node").style("background",function(t){return null!=t.children?"lightgrey":i(t.name)}).text(function(t){return t.name}).call(function(){this.style("left",function(t){return t.x+"px"}).style("top",function(t){return t.y+"px"}).style("width",function(t){return Math.max(0,t.dx-1)+"px"}).style("height",function(t){return Math.max(0,t.dy-1)+"px"})});return l}}})}).call(this)},{jquery:18}],20:[function(e,n,r){(function(){(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e,n;e=t;n=function(t,n){return function(r,i){var o,a,s,l,u,c,f,h,d,p,g,m,v,y,b,x,w,C,S,T,k,_,M,D,L;c={localeStrings:{vs:"vs",by:"by"}};i=e.extend(c,i);w=r.getRowKeys();0===w.length&&w.push([]);s=r.getColKeys();0===s.length&&s.push([]);p=function(){var t,e,n;n=[];for(t=0,e=w.length;e>t;t++){h=w[t];n.push(h.join("-"))}return n}();p.unshift("");m=0;l=[p];for(_=0,D=s.length;D>_;_++){a=s[_];b=[a.join("-")];m+=b[0].length;for(M=0,L=w.length;L>M;M++){x=w[M];o=r.getAggregator(x,a);b.push(null!=o.value()?o.value():null)}l.push(b)}C=T=r.aggregatorName+(r.valAttrs.length?"("+r.valAttrs.join(", ")+")":"");d=r.colAttrs.join("-");""!==d&&(C+=" "+i.localeStrings.vs+" "+d);f=r.rowAttrs.join("-");""!==f&&(C+=" "+i.localeStrings.by+" "+f);v={width:e(window).width()/1.4,height:e(window).height()/1.4,title:C,hAxis:{title:d,slantedText:m>50},vAxis:{title:T}};2===l[0].length&&""===l[0][1]&&(v.legend={position:"none"});for(g in n){S=n[g];v[g]=S}u=google.visualization.arrayToDataTable(l);y=e("<div style='width: 100%; height: 100%;'>");k=new google.visualization.ChartWrapper({dataTable:u,chartType:t,options:v});k.draw(y[0]);y.bind("dblclick",function(){var t;t=new google.visualization.ChartEditor;google.visualization.events.addListener(t,"ok",function(){return t.getChartWrapper().draw(y[0])});return t.openDialog(k)});return y}};return e.pivotUtilities.gchart_renderers={"Line Chart":n("LineChart"),"Bar Chart":n("ColumnChart"),"Stacked Bar Chart":n("ColumnChart",{isStacked:!0}),"Area Chart":n("AreaChart",{isStacked:!0})}})}).call(this)},{jquery:18}],21:[function(e,n,r){(function(){var i=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1},o=[].slice,a=function(t,e){return function(){return t.apply(e,arguments)}},s={}.hasOwnProperty;(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e,n,r,l,u,c,f,h,d,p,g,m,v,y,b,x,w;e=t;r=function(t,e,n){var r,i,o,a;t+="";i=t.split(".");o=i[0];a=i.length>1?n+i[1]:"";r=/(\d+)(\d{3})/;for(;r.test(o);)o=o.replace(r,"$1"+e+"$2");return o+a};g=function(t){var n;n={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:"",showZero:!1};t=e.extend(n,t);return function(e){var n;if(isNaN(e)||!isFinite(e))return"";if(0===e&&!t.showZero)return"";n=r((t.scaler*e).toFixed(t.digitsAfterDecimal),t.thousandsSep,t.decimalSep);return""+t.prefix+n+t.suffix}};y=g();b=g({digitsAfterDecimal:0});x=g({digitsAfterDecimal:1,scaler:100,suffix:"%"});l={count:function(t){null==t&&(t=b);return function(){return function(){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:t}}}},countUnique:function(t){null==t&&(t=b);return function(e){var n;n=e[0];return function(){return{uniq:[],push:function(t){var e;return e=t[n],i.call(this.uniq,e)<0?this.uniq.push(t[n]):void 0},value:function(){return this.uniq.length},format:t,numInputs:null!=n?0:1}}}},listUnique:function(t){return function(e){var n;n=e[0];return function(){return{uniq:[],push:function(t){var e;return e=t[n],i.call(this.uniq,e)<0?this.uniq.push(t[n]):void 0},value:function(){return this.uniq.join(t)},format:function(t){return t},numInputs:null!=n?0:1}}}},sum:function(t){null==t&&(t=y);return function(e){var n;n=e[0];return function(){return{sum:0,push:function(t){return isNaN(parseFloat(t[n]))?void 0:this.sum+=parseFloat(t[n])},value:function(){return this.sum},format:t,numInputs:null!=n?0:1}}}},average:function(t){null==t&&(t=y);return function(e){var n;n=e[0];return function(){return{sum:0,len:0,push:function(t){if(!isNaN(parseFloat(t[n]))){this.sum+=parseFloat(t[n]);return this.len++}},value:function(){return this.sum/this.len},format:t,numInputs:null!=n?0:1}}}},sumOverSum:function(t){null==t&&(t=y);return function(e){var n,r;r=e[0],n=e[1];return function(){return{sumNum:0,sumDenom:0,push:function(t){isNaN(parseFloat(t[r]))||(this.sumNum+=parseFloat(t[r]));return isNaN(parseFloat(t[n]))?void 0:this.sumDenom+=parseFloat(t[n])},value:function(){return this.sumNum/this.sumDenom},format:t,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(t,e){null==t&&(t=!0);null==e&&(e=y);return function(n){var r,i;i=n[0],r=n[1];return function(){return{sumNum:0,sumDenom:0,push:function(t){isNaN(parseFloat(t[i]))||(this.sumNum+=parseFloat(t[i]));return isNaN(parseFloat(t[r]))?void 0:this.sumDenom+=parseFloat(t[r])},value:function(){var e;e=t?1:-1;return(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*e*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:e,numInputs:null!=i&&null!=r?0:2}}}},fractionOf:function(t,e,n){null==e&&(e="total");null==n&&(n=x);return function(){var r;r=1<=arguments.length?o.call(arguments,0):[];return function(i,o,a){return{selector:{total:[[],[]],row:[o,[]],col:[[],a]}[e],inner:t.apply(null,r)(i,o,a),push:function(t){return this.inner.push(t)},format:n,value:function(){return this.inner.value()/i.getAggregator.apply(i,this.selector).inner.value()},numInputs:t.apply(null,r)().numInputs}}}}};u=function(t){return{Count:t.count(b),"Count Unique Values":t.countUnique(b),"List Unique Values":t.listUnique(", "),Sum:t.sum(y),"Integer Sum":t.sum(b),Average:t.average(y),"Sum over Sum":t.sumOverSum(y),"80% Upper Bound":t.sumOverSumBound80(!0,y),"80% Lower Bound":t.sumOverSumBound80(!1,y),"Sum as Fraction of Total":t.fractionOf(t.sum(),"total",x),"Sum as Fraction of Rows":t.fractionOf(t.sum(),"row",x),"Sum as Fraction of Columns":t.fractionOf(t.sum(),"col",x),"Count as Fraction of Total":t.fractionOf(t.count(),"total",x),"Count as Fraction of Rows":t.fractionOf(t.count(),"row",x),"Count as Fraction of Columns":t.fractionOf(t.count(),"col",x)}}(l);v={Table:function(t,e){return m(t,e)},"Table Barchart":function(t,n){return e(m(t,n)).barchart()},Heatmap:function(t,n){return e(m(t,n)).heatmap()},"Row Heatmap":function(t,n){return e(m(t,n)).heatmap("rowheatmap")},"Col Heatmap":function(t,n){return e(m(t,n)).heatmap("colheatmap")}};h={en:{aggregators:u,renderers:v,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter results",totals:"Totals",vs:"vs",by:"by"}}};d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];c=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];w=function(t){return("0"+t).substr(-2,2)};f={bin:function(t,e){return function(n){return n[t]-n[t]%e}},dateFormat:function(t,e,n,r){null==n&&(n=d);null==r&&(r=c);return function(i){var o;o=new Date(Date.parse(i[t]));return isNaN(o)?"":e.replace(/%(.)/g,function(t,e){switch(e){case"y":return o.getFullYear();case"m":return w(o.getMonth()+1);case"n":return n[o.getMonth()];case"d":return w(o.getDate());case"w":return r[o.getDay()];case"x":return o.getDay();case"H":return w(o.getHours());case"M":return w(o.getMinutes());case"S":return w(o.getSeconds());default:return"%"+e}})}}};p=function(t,e){var n,r,i,o,a,s,l;s=/(\d+)|(\D+)/g;a=/\d/;l=/^0/;if("number"==typeof t||"number"==typeof e)return isNaN(t)?1:isNaN(e)?-1:t-e;n=String(t).toLowerCase();i=String(e).toLowerCase();if(n===i)return 0;if(!a.test(n)||!a.test(i))return n>i?1:-1;n=n.match(s);i=i.match(s);for(;n.length&&i.length;){r=n.shift();o=i.shift();if(r!==o)return a.test(r)&&a.test(o)?r.replace(l,".0")-o.replace(l,".0"):r>o?1:-1}return n.length-i.length};e.pivotUtilities={aggregatorTemplates:l,aggregators:u,renderers:v,derivers:f,locales:h,naturalSort:p,numberFormat:g};n=function(){function n(t,e){this.getAggregator=a(this.getAggregator,this);this.getRowKeys=a(this.getRowKeys,this);this.getColKeys=a(this.getColKeys,this);this.sortKeys=a(this.sortKeys,this);this.arrSort=a(this.arrSort,this);this.natSort=a(this.natSort,this);var r=this;this.aggregator=e.aggregator;this.aggregatorName=e.aggregatorName;this.colAttrs=e.cols;this.rowAttrs=e.rows;this.valAttrs=e.vals;this.tree={};this.rowKeys=[];this.colKeys=[];this.rowTotals={};this.colTotals={};this.allTotal=this.aggregator(this,[],[]);this.sorted=!1;n.forEachRecord(t,e.derivedAttributes,function(t){return e.filter(t)?r.processRecord(t):void 0})}n.forEachRecord=function(n,r,i){var o,a,l,u,c,f,h,d,p,g,m,v;o=e.isEmptyObject(r)?i:function(t){var e,n,o;for(e in r){n=r[e];t[e]=null!=(o=n(t))?o:t[e]}return i(t)};if(e.isFunction(n))return n(o);if(e.isArray(n)){if(e.isArray(n[0])){m=[];for(l in n)if(s.call(n,l)){a=n[l];if(l>0){f={};g=n[0];for(u in g)if(s.call(g,u)){c=g[u];f[c]=a[u]}m.push(o(f))}}return m}v=[];for(d=0,p=n.length;p>d;d++){f=n[d];v.push(o(f))}return v}if(n instanceof t){h=[];e("thead > tr > th",n).each(function(){return h.push(e(this).text())});return e("tbody > tr",n).each(function(){f={};e("td",this).each(function(t){return f[h[t]]=e(this).text()});return o(f)})}throw new Error("unknown input format")};n.convertToArray=function(t){var e;e=[];n.forEachRecord(t,{},function(t){return e.push(t)});return e};n.prototype.natSort=function(t,e){return p(t,e)};n.prototype.arrSort=function(t,e){return this.natSort(t.join(),e.join())};n.prototype.sortKeys=function(){if(!this.sorted){this.rowKeys.sort(this.arrSort);this.colKeys.sort(this.arrSort)}return this.sorted=!0};n.prototype.getColKeys=function(){this.sortKeys();return this.colKeys};n.prototype.getRowKeys=function(){this.sortKeys();return this.rowKeys};n.prototype.processRecord=function(t){var e,n,r,i,o,a,s,l,u,c,f,h,d;e=[];i=[];c=this.colAttrs;for(a=0,l=c.length;l>a;a++){o=c[a];e.push(null!=(f=t[o])?f:"null")}h=this.rowAttrs;for(s=0,u=h.length;u>s;s++){o=h[s];i.push(null!=(d=t[o])?d:"null")}r=i.join(String.fromCharCode(0));n=e.join(String.fromCharCode(0));this.allTotal.push(t);if(0!==i.length){if(!this.rowTotals[r]){this.rowKeys.push(i);this.rowTotals[r]=this.aggregator(this,i,[])}this.rowTotals[r].push(t)}if(0!==e.length){if(!this.colTotals[n]){this.colKeys.push(e);this.colTotals[n]=this.aggregator(this,[],e)}this.colTotals[n].push(t)}if(0!==e.length&&0!==i.length){this.tree[r]||(this.tree[r]={});this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,i,e));return this.tree[r][n].push(t)}};n.prototype.getAggregator=function(t,e){var n,r,i;i=t.join(String.fromCharCode(0));r=e.join(String.fromCharCode(0));n=0===t.length&&0===e.length?this.allTotal:0===t.length?this.colTotals[r]:0===e.length?this.rowTotals[i]:this.tree[i][r];return null!=n?n:{value:function(){return null},format:function(){return""}}};return n}();m=function(t,n){var r,i,o,a,l,u,c,f,h,d,p,g,m,v,y,b,x,w,C,S,T;u={localeStrings:{totals:"Totals"}};n=e.extend(u,n);o=t.colAttrs;p=t.rowAttrs;m=t.getRowKeys();l=t.getColKeys();d=document.createElement("table");d.className="pvtTable";v=function(t,e,n){var r,i,o,a,s,l;if(0!==e){i=!0;for(a=s=0;n>=0?n>=s:s>=n;a=n>=0?++s:--s)t[e-1][a]!==t[e][a]&&(i=!1);if(i)return-1}r=0;for(;e+r<t.length;){o=!1;for(a=l=0;n>=0?n>=l:l>=n;a=n>=0?++l:--l)t[e][a]!==t[e+r][a]&&(o=!0);if(o)break;r++}return r};for(f in o)if(s.call(o,f)){i=o[f];w=document.createElement("tr");if(0===parseInt(f)&&0!==p.length){b=document.createElement("th");b.setAttribute("colspan",p.length);b.setAttribute("rowspan",o.length);w.appendChild(b)}b=document.createElement("th");b.className="pvtAxisLabel";b.textContent=i;w.appendChild(b);for(c in l)if(s.call(l,c)){a=l[c];T=v(l,parseInt(c),parseInt(f));if(-1!==T){b=document.createElement("th");b.className="pvtColLabel";b.textContent=a[f];b.setAttribute("colspan",T);parseInt(f)===o.length-1&&0!==p.length&&b.setAttribute("rowspan",2);w.appendChild(b)}}if(0===parseInt(f)){b=document.createElement("th");b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals;b.setAttribute("rowspan",o.length+(0===p.length?0:1));w.appendChild(b)}d.appendChild(w)}if(0!==p.length){w=document.createElement("tr");for(c in p)if(s.call(p,c)){h=p[c];b=document.createElement("th");b.className="pvtAxisLabel";b.textContent=h;w.appendChild(b)}b=document.createElement("th");if(0===o.length){b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals}w.appendChild(b);d.appendChild(w)}for(c in m)if(s.call(m,c)){g=m[c];w=document.createElement("tr");for(f in g)if(s.call(g,f)){C=g[f];T=v(m,parseInt(c),parseInt(f));if(-1!==T){b=document.createElement("th");b.className="pvtRowLabel";b.textContent=C;b.setAttribute("rowspan",T);parseInt(f)===p.length-1&&0!==o.length&&b.setAttribute("colspan",2);w.appendChild(b)}}for(f in l)if(s.call(l,f)){a=l[f];r=t.getAggregator(g,a);S=r.value();y=document.createElement("td");y.className="pvtVal row"+c+" col"+f;y.innerHTML=r.format(S);y.setAttribute("data-value",S);w.appendChild(y)}x=t.getAggregator(g,[]);S=x.value();y=document.createElement("td");y.className="pvtTotal rowTotal";y.innerHTML=x.format(S);y.setAttribute("data-value",S);y.setAttribute("data-for","row"+c);w.appendChild(y);d.appendChild(w)}w=document.createElement("tr");b=document.createElement("th");b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals;b.setAttribute("colspan",p.length+(0===o.length?0:1));w.appendChild(b);for(f in l)if(s.call(l,f)){a=l[f];x=t.getAggregator([],a);S=x.value();y=document.createElement("td");y.className="pvtTotal colTotal";y.innerHTML=x.format(S);y.setAttribute("data-value",S);y.setAttribute("data-for","col"+f);w.appendChild(y)}x=t.getAggregator([],[]);S=x.value();y=document.createElement("td");y.className="pvtGrandTotal";y.innerHTML=x.format(S);y.setAttribute("data-value",S);w.appendChild(y);d.appendChild(w);d.setAttribute("data-numrows",m.length);d.setAttribute("data-numcols",l.length);return d};e.fn.pivot=function(t,r){var i,o,a,s;i={cols:[],rows:[],filter:function(){return!0},aggregator:l.count()(),aggregatorName:"Count",derivedAttributes:{},renderer:m,rendererOptions:null,localeStrings:h.en.localeStrings};r=e.extend(i,r);a=null;try{o=new n(t,r);try{a=r.renderer(o,r.rendererOptions)}catch(u){"undefined"!=typeof console&&null!==console&&console.error(u.stack);a=e("<span>").html(r.localeStrings.renderError)}}catch(u){"undefined"!=typeof console&&null!==console&&console.error(u.stack);a=e("<span>").html(r.localeStrings.computeError)}s=this[0];for(;s.hasChildNodes();)s.removeChild(s.lastChild);return this.append(a)};e.fn.pivotUI=function(t,r,o,a){var l,u,c,f,d,g,m,v,y,b,x,w,C,S,T,k,_,M,D,L,A,N,E,j,I,P,H,O,F,R,W,z,q,U,B,V,X,G,$=this;null==o&&(o=!1);null==a&&(a="en");m={derivedAttributes:{},aggregators:h[a].aggregators,renderers:h[a].renderers,hiddenAttributes:[],menuLimit:200,cols:[],rows:[],vals:[],exclusions:{},unusedAttrsVertical:"auto",autoSortUnusedAttrs:!1,rendererOptions:{localeStrings:h[a].localeStrings},onRefresh:null,filter:function(){return!0},localeStrings:h[a].localeStrings};v=this.data("pivotUIOptions");w=null==v||o?e.extend(m,r):v;try{t=n.convertToArray(t);D=function(){var e,n;e=t[0];n=[];for(x in e)s.call(e,x)&&n.push(x);return n}();U=w.derivedAttributes;for(d in U)s.call(U,d)&&i.call(D,d)<0&&D.push(d);f={};for(P=0,R=D.length;R>P;P++){j=D[P];f[j]={}}n.forEachRecord(t,w.derivedAttributes,function(t){var e,n,r,i;i=[];for(x in t)if(s.call(t,x)){e=t[x];if(w.filter(t)){null==e&&(e="null");null==(r=(n=f[x])[e])&&(n[e]=0);i.push(f[x][e]++)}}return i});N=e("<table cellpadding='5'>");_=e("<td>");k=e("<select class='pvtRenderer'>").appendTo(_).bind("change",function(){return S()});B=w.renderers;for(j in B)s.call(B,j)&&e("<option>").val(j).html(j).appendTo(k);g=e("<td class='pvtAxisContainer pvtUnused'>");M=function(){var t,e,n;n=[];for(t=0,e=D.length;e>t;t++){d=D[t];i.call(w.hiddenAttributes,d)<0&&n.push(d)}return n}();E=!1;if("auto"===w.unusedAttrsVertical){c=0;for(H=0,W=M.length;W>H;H++){l=M[H];c+=l.length}E=c>120}g.addClass(w.unusedAttrsVertical===!0||E?"pvtVertList":"pvtHorizList");I=function(t){var n,r,o,a,s,l,u,c,h,d,m,v,b,C,T;u=function(){var e;e=[];for(x in f[t])e.push(x);return e}();l=!1;v=e("<div>").addClass("pvtFilterBox").hide();v.append(e("<h4>").text(""+t+" ("+u.length+")"));if(u.length>w.menuLimit)v.append(e("<p>").html(w.localeStrings.tooMany));else{r=e("<p>").appendTo(v);r.append(e("<button>").html(w.localeStrings.selectAll).bind("click",function(){return v.find("input:visible").prop("checked",!0)}));r.append(e("<button>").html(w.localeStrings.selectNone).bind("click",function(){return v.find("input:visible").prop("checked",!1)}));r.append(e("<input>").addClass("pvtSearch").attr("placeholder",w.localeStrings.filterResults).bind("keyup",function(){var t;t=e(this).val().toLowerCase();return e(this).parents(".pvtFilterBox").find("label span").each(function(){var n;n=e(this).text().toLowerCase().indexOf(t);return-1!==n?e(this).parent().show():e(this).parent().hide()})}));o=e("<div>").addClass("pvtCheckContainer").appendTo(v);T=u.sort(p);for(b=0,C=T.length;C>b;b++){x=T[b];m=f[t][x];a=e("<label>");s=w.exclusions[t]?i.call(w.exclusions[t],x)>=0:!1;l||(l=s);e("<input type='checkbox' class='pvtFilter'>").attr("checked",!s).data("filter",[t,x]).appendTo(a);a.append(e("<span>").text(""+x+" ("+m+")"));o.append(e("<p>").append(a))}}d=function(){var t;t=e(v).find("[type='checkbox']").length-e(v).find("[type='checkbox']:checked").length;t>0?n.addClass("pvtFilteredAttribute"):n.removeClass("pvtFilteredAttribute");return u.length>w.menuLimit?v.toggle():v.toggle(0,S)};e("<p>").appendTo(v).append(e("<button>").text("OK").bind("click",d));c=function(t){v.css({left:t.pageX,top:t.pageY}).toggle();e(".pvtSearch").val("");return e("label").show()};h=e("<span class='pvtTriangle'>").html(" &#x25BE;").bind("click",c);n=e("<li class='axis_"+y+"'>").append(e("<span class='pvtAttr'>").text(t).data("attrName",t).append(h));l&&n.addClass("pvtFilteredAttribute");g.append(n).append(v);return n.bind("dblclick",c)};for(y in M){d=M[y];I(d)}L=e("<tr>").appendTo(N);u=e("<select class='pvtAggregator'>").bind("change",function(){return S()});V=w.aggregators;for(j in V)s.call(V,j)&&u.append(e("<option>").val(j).html(j));e("<td class='pvtVals'>").appendTo(L).append(u).append(e("<br>"));e("<td class='pvtAxisContainer pvtHorizList pvtCols'>").appendTo(L);A=e("<tr>").appendTo(N);A.append(e("<td valign='top' class='pvtAxisContainer pvtRows'>"));C=e("<td valign='top' class='pvtRendererArea'>").appendTo(A);if(w.unusedAttrsVertical===!0||E){N.find("tr:nth-child(1)").prepend(_);N.find("tr:nth-child(2)").prepend(g)}else N.prepend(e("<tr>").append(_).append(g));this.html(N);X=w.cols;for(O=0,z=X.length;z>O;O++){j=X[O];this.find(".pvtCols").append(this.find(".axis_"+M.indexOf(j)))}G=w.rows;for(F=0,q=G.length;q>F;F++){j=G[F];this.find(".pvtRows").append(this.find(".axis_"+M.indexOf(j)))}null!=w.aggregatorName&&this.find(".pvtAggregator").val(w.aggregatorName);null!=w.rendererName&&this.find(".pvtRenderer").val(w.rendererName);b=!0;T=function(){var n,r,o,a,s,l,c,f,h,d,p,g,m,v;f={derivedAttributes:w.derivedAttributes,localeStrings:w.localeStrings,rendererOptions:w.rendererOptions,cols:[],rows:[]};s=null!=(v=w.aggregators[u.val()]([])().numInputs)?v:0;d=[];$.find(".pvtRows li span.pvtAttr").each(function(){return f.rows.push(e(this).data("attrName"))});$.find(".pvtCols li span.pvtAttr").each(function(){return f.cols.push(e(this).data("attrName"))});$.find(".pvtVals select.pvtAttrDropdown").each(function(){if(0===s)return e(this).remove();s--;return""!==e(this).val()?d.push(e(this).val()):void 0});if(0!==s){c=$.find(".pvtVals");for(j=g=0;s>=0?s>g:g>s;j=s>=0?++g:--g){a=e("<select class='pvtAttrDropdown'>").append(e("<option>")).bind("change",function(){return S()});for(m=0,p=M.length;p>m;m++){n=M[m];a.append(e("<option>").val(n).text(n))}c.append(a)}}if(b){d=w.vals;y=0;$.find(".pvtVals select.pvtAttrDropdown").each(function(){e(this).val(d[y]);return y++});b=!1}f.aggregatorName=u.val();f.vals=d;f.aggregator=w.aggregators[u.val()](d);f.renderer=w.renderers[k.val()];r={};$.find("input.pvtFilter").not(":checked").each(function(){var t;t=e(this).data("filter");return null!=r[t[0]]?r[t[0]].push(t[1]):r[t[0]]=[t[1]]});f.filter=function(t){var e,n;if(!w.filter(t))return!1;for(x in r){e=r[x];if(n=""+t[x],i.call(e,n)>=0)return!1}return!0};C.pivot(t,f);l=e.extend(w,{cols:f.cols,rows:f.rows,vals:d,exclusions:r,aggregatorName:u.val(),rendererName:k.val()});$.data("pivotUIOptions",l);if(w.autoSortUnusedAttrs){o=e.pivotUtilities.naturalSort;h=$.find("td.pvtUnused.pvtAxisContainer");e(h).children("li").sort(function(t,n){return o(e(t).text(),e(n).text())}).appendTo(h)}C.css("opacity",1);return null!=w.onRefresh?w.onRefresh(l):void 0};S=function(){C.css("opacity",.5);return setTimeout(T,10)};S();this.find(".pvtAxisContainer").sortable({update:function(t,e){return null==e.sender?S():void 0},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(Y){"undefined"!=typeof console&&null!==console&&console.error(Y.stack);this.html(w.localeStrings.uiRenderError)}return this};e.fn.heatmap=function(t){var n,r,i,o,a,s,l,u,c=this;null==t&&(t="heatmap");s=this.data("numrows");a=this.data("numcols");n=function(t,e,n){var r;r=function(){switch(t){case"red":return function(t){return"ff"+t+t};case"green":return function(t){return""+t+"ff"+t};case"blue":return function(t){return""+t+t+"ff"}}}();return function(t){var i,o;o=255-Math.round(255*(t-e)/(n-e));i=o.toString(16).split(".")[0];1===i.length&&(i=0+i);return r(i)}};r=function(t,r){var i,o,a;o=function(n){return c.find(t).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};a=[];o(function(t){return a.push(t)});i=n(r,Math.min.apply(Math,a),Math.max.apply(Math,a));return o(function(t,e){return e.css("background-color","#"+i(t))})};switch(t){case"heatmap":r(".pvtVal","red");break;case"rowheatmap":for(i=l=0;s>=0?s>l:l>s;i=s>=0?++l:--l)r(".pvtVal.row"+i,"red");break;case"colheatmap":for(o=u=0;a>=0?a>u:u>a;o=a>=0?++u:--u)r(".pvtVal.col"+o,"red")}r(".pvtTotal.rowTotal","red");r(".pvtTotal.colTotal","red");return this};return e.fn.barchart=function(){var t,n,r,i,o,a=this;i=this.data("numrows");r=this.data("numcols");t=function(t){var n,r,i,o;n=function(n){return a.find(t).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};o=[];n(function(t){return o.push(t)});r=Math.max.apply(Math,o);i=function(t){return 100*t/(1.4*r)};return n(function(t,n){var r,o;r=n.text();o=e("<div>").css({position:"relative",height:"55px"});o.append(e("<div>").css({position:"absolute",bottom:0,left:0,right:0,height:i(t)+"%","background-color":"gray"}));o.append(e("<div>").text(r).css({position:"relative","padding-left":"5px","padding-right":"5px"}));return n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(o)})};for(n=o=0;i>=0?i>o:o>i;n=i>=0?++o:--o)t(".pvtVal.row"+n);t(".pvtTotal.colTotal");return this}})}).call(this)},{jquery:18}],22:[function(e,n){(function(e){function r(){try{return l in e&&e[l]}catch(t){return!1}}function i(t){return t.replace(/^d/,"___$&").replace(p,"___")}var o,a={},s=e.document,l="localStorage",u="script";a.disabled=!1;a.version="1.3.17";a.set=function(){};a.get=function(){};a.has=function(t){return void 0!==a.get(t)};a.remove=function(){};a.clear=function(){};a.transact=function(t,e,n){if(null==n){n=e;e=null}null==e&&(e={});var r=a.get(t,e);n(r);a.set(t,r)};a.getAll=function(){};a.forEach=function(){};a.serialize=function(t){return JSON.stringify(t)};a.deserialize=function(t){if("string"!=typeof t)return void 0;try{return JSON.parse(t)}catch(e){return t||void 0}};if(r()){o=e[l];a.set=function(t,e){if(void 0===e)return a.remove(t);o.setItem(t,a.serialize(e));return e};a.get=function(t,e){var n=a.deserialize(o.getItem(t));return void 0===n?e:n};a.remove=function(t){o.removeItem(t)};a.clear=function(){o.clear()};a.getAll=function(){var t={};a.forEach(function(e,n){t[e]=n});return t};a.forEach=function(t){for(var e=0;e<o.length;e++){var n=o.key(e);t(n,a.get(n))}}}else if(s.documentElement.addBehavior){var c,f;try{f=new ActiveXObject("htmlfile");f.open();f.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');f.close();c=f.w.frames[0].document;o=c.createElement("div")}catch(h){o=s.createElement("div");c=s.body}var d=function(t){return function(){var e=Array.prototype.slice.call(arguments,0);e.unshift(o);c.appendChild(o);o.addBehavior("#default#userData");o.load(l);var n=t.apply(a,e);c.removeChild(o);return n}},p=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=d(function(t,e,n){e=i(e);if(void 0===n)return a.remove(e);t.setAttribute(e,a.serialize(n));t.save(l);return n});a.get=d(function(t,e,n){e=i(e);var r=a.deserialize(t.getAttribute(e));return void 0===r?n:r});a.remove=d(function(t,e){e=i(e);t.removeAttribute(e);t.save(l)});a.clear=d(function(t){var e=t.XMLDocument.documentElement.attributes;t.load(l);for(var n,r=0;n=e[r];r++)t.removeAttribute(n.name);t.save(l)});a.getAll=function(){var t={};a.forEach(function(e,n){t[e]=n});return t};a.forEach=d(function(t,e){for(var n,r=t.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)e(n.name,a.deserialize(t.getAttribute(n.name)))})}try{var g="__storejs__";a.set(g,g);a.get(g)!=g&&(a.disabled=!0);a.remove(g)}catch(h){a.disabled=!0}a.enabled=!a.disabled;"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=a:"function"==typeof t&&t.amd?t(a):e.store=a})(Function("return this")())},{}],23:[function(t,e){e.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],24:[function(t,e){window.console=window.console||{log:function(){}};e.exports={storage:t("./storage.js"),svg:t("./svg.js"),version:{"yasgui-utils":t("../package.json").version}}},{"../package.json":23,"./storage.js":25,"./svg.js":26}],25:[function(t,e){{var n=t("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};e.exports={set:function(t,e,i){if(t&&e){"string"==typeof i&&(i=r[i]());e.documentElement&&(e=(new XMLSerializer).serializeToString(e.documentElement));n.set(t,{val:e,exp:i,time:(new Date).getTime()})}},remove:function(t){t&&n.remove(t)},get:function(t){if(t){var e=n.get(t);return e?e.exp&&(new Date).getTime()-e.time>e.exp?null:e.val:null}return null}}}},{store:22}],26:[function(t,e){e.exports={draw:function(t,n){if(t){var r=e.exports.getElement(n);r&&(t.append?t.append(r):t.appendChild(r))}},getElement:function(t){if(t&&0==t.indexOf("<svg")){var e=new DOMParser,n=e.parseFromString(t,"text/xml"),r=n.documentElement,i=document.createElement("div");i.className="svgImg";i.appendChild(r);return i}return!1}}},{}],27:[function(t,e){e.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.4.0",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1","gulp-html-replace":"^1.4.1","browserify-shim":"^3.8.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1",pivottable:"^1.2.2","jquery-ui":"^1.10.5",d3:"^3.4.13"},"browserify-shim":{google:"global:google"},browserify:{transform:["browserify-shim"]},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"datatables",global:"jQuery"},datatables:{require:"datatables",global:"jQuery"},d3:{require:"d3",global:"d3"},"jquery-ui/sortable":{require:"jquery-ui/sortable",global:"jQuery"},pivottable:{require:"pivottable",global:"jQuery"}}}},{}],28:[function(t,e){"use strict";e.exports=function(t){var e='"',n=",",r="\n",i=t.head.vars,o=t.results.bindings,a=function(){for(var t=0;t<i.length;t++)u(i[t]);f+=r},s=function(){for(var t=0;t<o.length;t++){l(o[t]);f+=r}},l=function(t){for(var e=0;e<i.length;e++){var n=i[e];u(t.hasOwnProperty(n)?t[n].value:"")}},u=function(t){t.replace(e,e+e);c(t)&&(t=e+t+e);f+=" "+t+" "+n},c=function(t){var r=!1;t.match("[\\w|"+n+"|"+e+"]")&&(r=!0);return r},f="";a();s();return f}},{}],29:[function(t,e){"use strict";var n=t("jquery"),r=e.exports=function(e){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(e.resultsContainer);var i=e.results.getBoolean(),o=null,a=null;if(i===!0){o="check";a="True"}else if(i===!1){o="cross";a="False"}else{r.width("140");a="Could not find boolean value in response"}o&&t("yasgui-utils").svg.draw(r,t("./imgs.js")[o]);n("<span></span>").text(a).appendTo(r)},o=function(){return e.results.getBoolean&&(e.results.getBoolean()===!0||0==e.results.getBoolean())};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":t("../package.json").version,jquery:n.fn.jquery}},{"../package.json":27,"./imgs.js":34,jquery:18,"yasgui-utils":24}],30:[function(t,e){"use strict";var n=t("jquery");e.exports={output:"table",useGoogleCharts:!0,outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{prefix:function(t){return"yasr_"+n(t.container).closest("[id]").attr("id")+"_"},outputSelector:function(){return"selector"},results:{id:function(t){return"results_"+n(t.container).closest("[id]").attr("id")},key:"results",maxSize:1e5}}}},{jquery:18}],31:[function(t,e){"use strict";var n=t("jquery"),r=e.exports=function(t){var e=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){var r=t.results.getException(); e.empty().appendTo(t.resultsContainer);var i="Error";r.statusText&&r.statusText.length<100&&(i=r.statusText);void 0!=r.status&&(i+=" (#"+r.status+")");e.append(n("<span>",{"class":"exception"}).text(i));var o=null;r.responseText?o=r.responseText:"string"==typeof r&&(o=r);o&&e.append(n("<pre>").text(o))}),o=function(t){return t.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:18}],32:[function(t,e){(function(n){var r=t("events").EventEmitter,i=(t("jquery"),!1),o=!1,a=function(){r.call(this);var t=this;this.init=function(){if(o||("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)||i)("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)?t.emit("initError"):o&&t.emit("initError");else{i=!0;s("//google.com/jsapi",function(){i=!1;t.emit("initDone")});var e=100,r=6e3,a=+new Date,l=function(){if(!("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null))if(+new Date-a>r){o=!0;i=!1;t.emit("initError")}else setTimeout(l,e)};l()}};this.googleLoad=function(){var e=function(){("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).load("visualization","1",{packages:["corechart","charteditor"],callback:function(){t.emit("done")}})};if(i){t.once("initDone",e);t.once("initError",function(){t.emit("error","Could not load google loader")})}else if("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)e();else if(o)t.emit("error","Could not load google loader");else{t.once("initDone",e);t.once("initError",function(){t.emit("error","Could not load google loader")})}}},s=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.readyState?n.onreadystatechange=function(){if("loaded"==n.readyState||"complete"==n.readyState){n.onreadystatechange=null;e()}}:n.onload=function(){e()};n.src=t;document.body.appendChild(n)};a.prototype=new r;e.exports=new a}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{events:4,jquery:18}],33:[function(t,e){(function(n){"use strict";function r(t,e,n){function r(t,e,o){var l,u,c,f,h,d,p,g;if(null==t||null==e)return t===e;if(t.__placeholder__||e.__placeholder__)return!0;if(t===e)return 0!==t||1/t==1/e;l=i.call(t);if(i.call(e)!=l)return!1;switch(l){case"[object String]":return t==String(e);case"[object Number]":return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case"[object Date]":case"[object Boolean]":return+t==+e;case"[object RegExp]":return t.source==e.source&&t.global==e.global&&t.multiline==e.multiline&&t.ignoreCase==e.ignoreCase}if("object"!=typeof t||"object"!=typeof e)return!1;u=o.length;for(;u--;)if(o[u]==t)return!0;o.push(t);c=0;f=!0;if("[object Array]"==l){h=t.length;d=e.length;if(s){switch(n){case"===":f=h===d;break;case"<==":f=d>=h;break;case"<<=":f=d>h}c=h;s=!1}else{f=h===d;c=h}if(f)for(;c--&&(f=c in t==c in e&&r(t[c],e[c],o)););}else{if("constructor"in t!="constructor"in e||t.constructor!=e.constructor)return!1;for(p in t)if(a(t,p)){c++;if(!(f=a(e,p)&&r(t[p],e[p],o)))break}if(f){g=0;for(p in e)a(e,p)&&++g;if(s)f="<<="===n?g>c:"<=="===n?g>=c:c===g;else{s=!1;f=c===g}}}o.pop();return f}var i={}.toString,o={}.hasOwnProperty,a=function(t,e){return o.call(t,e)},s=!0;return r(t,e,[])}var i=t("jquery"),o=t("./utils.js"),a=t("yasgui-utils"),s=e.exports=function(e){var l=i.extend(!0,{},s.defaults),u=e.container.closest("[id]").attr("id");null==e.options.gchart&&(e.options.gchart={});var c=e.getPersistencyId("motionchart"),f=e.getPersistencyId("chartConfig");null==e.options.gchart.motionChartState&&(e.options.gchart.motionChartState=a.storage.get(c));null==e.options.gchart.chartConfig&&(e.options.gchart.chartConfig=a.storage.get(f));var h=null,d=function(t){var i="undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null;h=new i.visualization.ChartEditor;i.visualization.events.addListener(h,"ok",function(){var t,n;t=h.getChartWrapper();if(!r(t.getChartType,"MotionChart","===")){e.options.gchart.motionChartState=t.n;a.storage.set(c,e.options.gchart.motionChartState);t.setOption("state",e.options.gchart.motionChartState);i.visualization.events.addListener(t,"ready",function(){var n;n=t.getChart();i.visualization.events.addListener(n,"statechange",function(){e.options.gchart.motionChartState=n.getState();a.storage.set(c,e.options.gchart.motionChartState)})})}n=t.getDataTable();t.setDataTable(null);e.options.gchart.chartConfig=t.toJSON();a.storage.set(f,e.options.gchart.chartConfig);t.setDataTable(n);t.draw()});t&&t()};return{name:"Google Chart",hideFromSelection:!1,priority:7,canHandleResults:function(t){var e,n;return null!=(e=t.results)&&(n=e.getVariables())&&n.length>0},getDownloadInfo:function(){if(!e.results)return null;var t=e.resultsContainer.find("svg");return 0==t.length?null:{getContent:function(){return t[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}},draw:function(){var r=function(){e.resultsContainer.empty();var t=u+"_gchartWrapper",n=null;e.resultsContainer.append(i("<button>",{"class":"openGchartBtn yasr_btn"}).text("Chart Config").click(function(){h.openDialog(n)})).append(i("<div>",{id:t,"class":"gchartWrapper"}));var r=new google.visualization.DataTable,s=e.results.getAsJson();s.head.vars.forEach(function(t){var e=o.getGoogleType(s.results.bindings[0][t]);r.addColumn(e,t)});var f=null;e.options.getUsedPrefixes&&(f="function"==typeof e.options.getUsedPrefixes?e.options.getUsedPrefixes(e):e.options.getUsedPrefixes);s.results.bindings.forEach(function(t){var e=[];s.head.vars.forEach(function(n){e.push(o.castGoogleType(t[n],f))});r.addRow(e)});if(e.options.gchart.chartConfig){n=new google.visualization.ChartWrapper(e.options.gchart.chartConfig);if("MotionChart"===n.getChartType()&&null!=e.options.gchart.motionChartState){n.setOption("state",e.options.gchart.motionChartState);google.visualization.events.addListener(n,"ready",function(){var t;t=n.getChart();google.visualization.events.addListener(t,"statechange",function(){e.options.gchart.motionChartState=t.getState();a.storage.set(c,e.options.gchart.motionChartState)})})}n.setDataTable(r)}else n=new google.visualization.ChartWrapper({chartType:"Table",dataTable:r,containerId:t});n.setOption("width",l.width);n.setOption("height",l.height);n.draw();e.updateHeader()};("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null)&&("undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null).visualization&&h?r():t("./gChartLoader.js").on("done",function(){d();r()}).on("error",function(){console.log("errorrr")}).googleLoad()}}};s.defaults={height:"600px",width:"100%",persistencyId:"gchart"}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./gChartLoader.js":32,"./utils.js":45,jquery:18,"yasgui-utils":24}],34:[function(t,e){"use strict";e.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',move:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_11656_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="753" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="287" inkscape:window-y="249" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><polygon points="33,83 50,100 67,83 54,83 54,17 67,17 50,0 33,17 46,17 46,83 " transform="translate(-7.962963,-10)" /><polygon points="83,67 100,50 83,33 83,46 17,46 17,33 0,50 17,67 17,54 83,54 " transform="translate(-7.962963,-10)" /></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}},{}],35:[function(t,e){"use strict";var n=t("jquery"),r=t("yasgui-utils");console=console||{log:function(){}};var i=e.exports=function(e,a,s){var l={};l.options=n.extend(!0,{},i.defaults,a);l.container=n("<div class='yasr'></div>").appendTo(e);l.header=n("<div class='yasr_header'></div>").appendTo(l.container);l.resultsContainer=n("<div class='yasr_results'></div>").appendTo(l.container);l.storage=r.storage;var u=null;l.getPersistencyId=function(t){null===u&&(u=l.options.persistency&&l.options.persistency.prefix?"string"==typeof l.options.persistency.prefix?l.options.persistency.prefix:l.options.persistency.prefix(l):!1);return u&&t?u+("string"==typeof t?t:t(l)):null};l.options.useGoogleCharts&&t("./gChartLoader.js").once("initError",function(){l.options.useGoogleCharts=!1}).init();l.plugins={};for(var c in i.plugins)l.plugins[c]=new i.plugins[c](l);l.updateHeader=function(){var t=l.header.find(".yasr_downloadIcon").removeAttr("title"),e=l.plugins[l.options.output];if(e){var n=e.getDownloadInfo?e.getDownloadInfo():null;if(n){n.buttonTitle&&t.attr("title",n.buttonTitle);t.prop("disabled",!1);t.find("path").each(function(){this.style.fill="black"})}else{t.prop("disabled",!0).prop("title","Download not supported for this result representation");t.find("path").each(function(){this.style.fill="gray"})}}};l.draw=function(t){if(!l.results)return!1;t||(t=l.options.output);var e=null,r=-1,i=[];for(var o in l.plugins)if(l.plugins[o].canHandleResults(l)){var a=l.plugins[o].getPriority;"function"==typeof a&&(a=a(l));if(null!=a&&void 0!=a&&a>r){r=a;e=o}}else i.push(o);f(i);if(t in l.plugins&&l.plugins[t].canHandleResults(l)){n(l.resultsContainer).empty();l.plugins[t].draw();return!0}if(e){n(l.resultsContainer).empty();l.plugins[e].draw();return!0}return!1};var f=function(t){l.header.find(".yasr_btnGroup .yasr_btn").removeClass("disabled");t.forEach(function(t){l.header.find(".yasr_btnGroup .select_"+t).addClass("disabled")})};l.somethingDrawn=function(){return!l.resultsContainer.is(":empty")};l.setResponse=function(e,n,i){try{l.results=t("./parsers/wrapper.js")(e,n,i)}catch(o){l.results={getException:function(){return o}}}l.draw();var a=l.getPersistencyId(l.options.persistency.results.key);a&&(l.results.getOriginalResponseAsString&&l.results.getOriginalResponseAsString().length<l.options.persistency.results.maxSize?r.storage.set(a,l.results.getAsStoreObject(),"month"):r.storage.remove(a))};var h=l.getPersistencyId(l.options.persistency.outputSelector);if(h){var d=r.storage.get(h);d&&(l.options.output=d)}o(l);if(!s&&l.options.persistency&&l.options.persistency.results){var p,g=l.getPersistencyId(l.options.persistency.results.key);g&&(p=r.storage.get(g));if(!p&&l.options.persistency.results.id){var m="string"==typeof l.options.persistency.results.id?l.options.persistency.results.id:l.options.persistency.results.id(l);if(m){p=r.storage.get(m);p&&r.storage.remove(m)}}p&&(n.isArray(p)?l.setResponse.apply(this,p):l.setResponse(p))}s&&l.setResponse(s);l.updateHeader();return l},o=function(e){var i=function(){var t=n('<div class="yasr_btnGroup"></div>');n.each(e.plugins,function(i,o){if(!o.hideFromSelection){var a=o.name||i,s=n("<button class='yasr_btn'></button>").text(a).addClass("select_"+i).click(function(){t.find("button.selected").removeClass("selected");n(this).addClass("selected");e.options.output=i;var o=e.getPersistencyId(e.options.persistency.outputSelector);o&&r.storage.set(o,e.options.output,"month");e.draw();e.updateHeader()}).appendTo(t);e.options.output==i&&s.addClass("selected")}});t.children().length>1&&e.header.append(t)},o=function(){var r=function(t,e){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([t],{type:e});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").download)).click(function(){var t=e.plugins[e.options.output];if(t&&t.getDownloadInfo){var i=t.getDownloadInfo(),o=r(i.getContent(),i.contentType?i.contentType:"text/plain"),a=n("<a></a>");a.attr("href",o);a.attr("download",i.filename);a.get(0).click()}});e.header.append(i)},a=function(){var r=n("<button class='yasr_btn btn_fullscreen btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").fullscreen)).click(function(){e.container.addClass("yasr_fullscreen")});e.header.append(r)},s=function(){var r=n("<button class='yasr_btn btn_smallscreen btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").smallscreen)).click(function(){e.container.removeClass("yasr_fullscreen")});e.header.append(r)};a();s();e.options.drawOutputSelector&&i();e.options.drawDownloadIcon&&o()};i.plugins={};i.registerOutput=function(t,e){i.plugins[t]=e};i.defaults=t("./defaults.js");i.version={YASR:t("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":t("yasgui-utils").version};i.$=n;try{i.registerOutput("boolean",t("./boolean.js"))}catch(a){}try{i.registerOutput("rawResponse",t("./rawResponse.js"))}catch(a){}try{i.registerOutput("table",t("./table.js"))}catch(a){}try{i.registerOutput("error",t("./error.js"))}catch(a){}try{i.registerOutput("pivot",t("./pivot.js"))}catch(a){}if(i.defaults.useGoogleCharts)try{i.registerOutput("gchart",t("./gchart.js"))}catch(a){}},{"../package.json":27,"./boolean.js":29,"./defaults.js":30,"./error.js":31,"./gChartLoader.js":32,"./gchart.js":33,"./imgs.js":34,"./parsers/wrapper.js":40,"./pivot.js":42,"./rawResponse.js":43,"./table.js":44,jquery:18,"yasgui-utils":24}],36:[function(t,e){"use strict";t("jquery"),e.exports=function(e){return t("./dlv.js")(e,",")}},{"./dlv.js":37,jquery:18}],37:[function(t,e){"use strict";var n=jQuery=t("jquery");t("../../lib/jquery.csv-0.71.js");e.exports=function(t,e){var r={},i=n.csv.toArrays(t,{separator:e}),o=function(t){return 0==t.indexOf("http")?"uri":null},a=function(){if(2==i.length&&1==i[0].length&&1==i[1].length&&"boolean"==i[0][0]&&("1"==i[1][0]||"0"==i[1][0])){r.boolean="1"==i[1][0]?!0:!1;return!0}return!1},s=function(){if(i.length>0&&i[0].length>0){r.head={vars:i[0]};return!0}return!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var t=1;t<i.length;t++){for(var e={},n=0;n<i[t].length;n++){var a=r.head.vars[n];if(a){var s=i[t][n],l=o(s);e[a]={value:s};l&&(e[a].type=l)}}r.results.bindings.push(e)}r.head={vars:i[0]};return!0}return!1},u=a();if(!u){var c=s();c&&l()}return r}},{"../../lib/jquery.csv-0.71.js":3,jquery:18}],38:[function(t,e){"use strict";t("jquery"),e.exports=function(t){if("string"==typeof t)try{return JSON.parse(t)}catch(e){return!1}return"object"==typeof t&&t.constructor==={}.constructor?t:!1}},{jquery:18}],39:[function(t,e){"use strict";t("jquery"),e.exports=function(e){return t("./dlv.js")(e," ")}},{"./dlv.js":37,jquery:18}],40:[function(t,e){"use strict";t("jquery"),e.exports=function(e,n,r){var i={xml:t("./xml.js"),json:t("./json.js"),tsv:t("./tsv.js"),csv:t("./csv.js")},o=null,a=null,s=null,l=null,u=null,c=function(){if("object"==typeof e){if(e.exception)u=e.exception;else if(void 0!=e.status&&(e.status>=300||0===e.status)){u={status:e.status};"string"==typeof r&&(u.errorString=r);e.responseText&&(u.responseText=e.responseText);e.statusText&&(u.statusText=e.statusText)}if(e.contentType)o=e.contentType.toLowerCase();else if(e.getResponseHeader&&e.getResponseHeader("content-type")){var t=e.getResponseHeader("content-type").trim().toLowerCase();t.length>0&&(o=t)}e.response?a=e.response:n||r||(a=e)}u||a||(a=e.responseText?e.responseText:e)},f=function(){if(s)return s;if(s===!1||u)return!1;var t=function(){if(o)if(o.indexOf("json")>-1){try{s=i.json(a)}catch(t){u=t}l="json"}else if(o.indexOf("xml")>-1){try{s=i.xml(a)}catch(t){u=t}l="xml"}else if(o.indexOf("csv")>-1){try{s=i.csv(a)}catch(t){u=t}l="csv"}else if(o.indexOf("tab-separated")>-1){try{s=i.tsv(a) }catch(t){u=t}l="tsv"}},e=function(){s=i.json(a);if(s)l="json";else try{s=i.xml(a);s&&(l="xml")}catch(t){}};t();s||e();s||(s=!1);return s},h=function(){var t=f();return t&&"head"in t?t.head.vars:null},d=function(){var t=f();return t&&"results"in t?t.results.bindings:null},p=function(){var t=f();return t&&"boolean"in t?t.boolean:null},g=function(){return a},m=function(){var t="";"string"==typeof a?t=a:"json"==l?t=JSON.stringify(a,void 0,2):"xml"==l&&(t=(new XMLSerializer).serializeToString(a));return t},v=function(){return u},y=function(){null==l&&f();return l},b=function(){var t={};if(e.status){t.status=e.status;t.responseText=e.responseText;t.statusText=e.statusText;t.contentType=o}else t=e;var i=n,a=void 0;"string"==typeof r&&(a=r);return[t,i,a]};c();s=f();return{getAsStoreObject:b,getAsJson:f,getOriginalResponse:g,getOriginalResponseAsString:m,getOriginalContentType:function(){return o},getVariables:h,getBindings:d,getBoolean:p,getType:y,getException:v}}},{"./csv.js":36,"./json.js":38,"./tsv.js":39,"./xml.js":41,jquery:18}],41:[function(t,e){"use strict";{var n=t("jquery");e.exports=function(t){var e=function(t){a.head={};for(var e=0;e<t.childNodes.length;e++){var n=t.childNodes[e];if("variable"==n.nodeName){a.head.vars||(a.head.vars=[]);var r=n.getAttribute("name");r&&a.head.vars.push(r)}}},r=function(t){a.results={};a.results.bindings=[];for(var e=0;e<t.childNodes.length;e++){for(var n=t.childNodes[e],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var s=o.getAttribute("name");if(s){r=r||{};r[s]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){r[s].type=c;r[s].value=u.innerHTML;var f=u.getAttribute("datatype");f&&(r[s].datatype=f)}}}}}r&&a.results.bindings.push(r)}},i=function(t){a.boolean="true"==t.innerHTML?!0:!1},o=null;"string"==typeof t?o=n.parseXML(t):n.isXMLDoc(t)&&(o=t);var t=null;if(!(o.childNodes.length>0))return null;t=o.childNodes[0];for(var a={},s=0;s<t.childNodes.length;s++){var l=t.childNodes[s];"head"==l.nodeName&&e(l);"results"==l.nodeName&&r(l);"boolean"==l.nodeName&&i(l)}return a}}},{jquery:18}],42:[function(t,e){"use strict";var n=t("jquery"),r=t("./utils.js"),i=t("yasgui-utils"),o=t("./imgs.js");t("jquery-ui/sortable");t("pivottable");if(!n.fn.pivotUI)throw new Error("Pivot lib not loaded");var a=e.exports=function(e){var s=n.extend(!0,{},a.defaults);if(s.useD3Chart){try{var l=t("d3");l&&t("../node_modules/pivottable/dist/d3_renderers.js")}catch(u){}n.pivotUtilities.d3_renderers&&n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.d3_renderers)}var c,f=null,h=function(){var t=e.results.getVariables();if(!s.mergeLabelsWithUris)return t;var n=[];f="string"==typeof s.mergeLabelsWithUris?s.mergeLabelsWithUris:"Label";t.forEach(function(e){-1!==e.indexOf(f,e.length-f.length)&&t.indexOf(e.substring(0,e.length-f.length))>=0||n.push(e)});return n},d=function(t){var n=h(),i=null;e.options.getUsedPrefixes&&(i="function"==typeof e.options.getUsedPrefixes?e.options.getUsedPrefixes(e):e.options.getUsedPrefixes);e.results.getBindings().forEach(function(e){var o={};n.forEach(function(t){if(t in e){var n=e[t].value;f&&e[t+f]?n=e[t+f].value:"uri"==e[t].type&&(n=r.uriToPrefixed(i,n));o[t]=n}else o[t]=null});t(o)})},p=e.getPersistencyId(s.persistencyId),g=function(){var t=i.storage.get(p);if(t){var r=e.results.getVariables(),o=!0;t.cols.forEach(function(t){r.indexOf(t)<0&&(o=!1)});o&&t.rows.forEach(function(t){r.indexOf(t)<0&&(o=!1)});if(!o){t.cols=[];t.rows=[]}n.pivotUtilities.renderers[t.rendererName]||delete t.rendererName}else t={};return t},m=function(){var r=function(){var t=function(t){if(p){var n={cols:t.cols,rows:t.rows,rendererName:t.rendererName,aggregatorName:t.aggregatorName,vals:t.vals};i.storage.set(p,n,"month")}t.rendererName.toLowerCase().indexOf(" chart")>=0?r.show():r.hide();e.updateHeader()},r=n("<button>",{"class":"openPivotGchart yasr_btn"}).text("Chart Config").click(function(){c.find('div[dir="ltr"]').dblclick()}).appendTo(e.resultsContainer);c=n("<div>",{"class":"pivotTable"}).appendTo(n(e.resultsContainer));var s=n.extend(!0,{},g(),a.defaults.pivotTable);s.onRefresh=function(){var e=s.onRefresh;return function(n){t(n);e&&e(n)}}();window.pivot=c.pivotUI(d,s);var l=n(i.svg.getElement(o.move));c.find(".pvtTriangle").replaceWith(l);n(".pvtCols").prepend(n("<div>",{"class":"containerHeader"}).text("Columns"));n(".pvtRows").prepend(n("<div>",{"class":"containerHeader"}).text("Rows"));n(".pvtUnused").prepend(n("<div>",{"class":"containerHeader"}).text("Available Variables"));n(".pvtVals").prepend(n("<div>",{"class":"containerHeader"}).text("Cells"));setTimeout(e.updateHeader,400)};e.options.useGoogleCharts&&s.useGoogleCharts&&!n.pivotUtilities.gchart_renderers?t("./gChartLoader.js").on("done",function(){try{t("../node_modules/pivottable/dist/gchart_renderers.js");n.extend(!0,n.pivotUtilities.renderers,n.pivotUtilities.gchart_renderers)}catch(e){s.useGoogleCharts=!1}r()}).on("error",function(){console.log("could not load gchart");s.useGoogleCharts=!1;r()}).googleLoad():r()},v=function(){return e.results&&e.results.getVariables&&e.results.getVariables()&&e.results.getVariables().length>0},y=function(){if(!e.results)return null;var t=e.resultsContainer.find(".pvtRendererArea svg");return 0==t.length?null:{getContent:function(){return t[0].outerHTML},filename:"queryResults.svg",contentType:"image/svg+xml",buttonTitle:"Download SVG Image"}};return{getDownloadInfo:y,options:s,draw:m,name:"Pivot Table",canHandleResults:v,getPriority:4}};a.defaults={mergeLabelsWithUris:!1,useGoogleCharts:!0,useD3Chart:!0,persistencyId:"pivot",pivotTable:{}};a.version={"YASR-rawResponse":t("../package.json").version,jquery:n.fn.jquery}},{"../node_modules/pivottable/dist/d3_renderers.js":19,"../node_modules/pivottable/dist/gchart_renderers.js":20,"../package.json":27,"./gChartLoader.js":32,"./imgs.js":34,"./utils.js":45,d3:13,jquery:18,"jquery-ui/sortable":16,pivottable:21,"yasgui-utils":24}],43:[function(t,e){"use strict";var n=t("jquery"),r=t("codemirror");t("codemirror/addon/fold/foldcode.js");t("codemirror/addon/fold/foldgutter.js");t("codemirror/addon/fold/xml-fold.js");t("codemirror/addon/fold/brace-fold.js");t("codemirror/addon/edit/matchbrackets.js");t("codemirror/mode/xml/xml.js");t("codemirror/mode/javascript/javascript.js");var i=e.exports=function(t){var e=n.extend(!0,{},i.defaults),o=null,a=function(){var n=e.CodeMirror;n.value=t.results.getOriginalResponseAsString();var i=t.results.getType();if(i){"json"==i&&(i={name:"javascript",json:!0});n.mode=i}o=r(t.resultsContainer.get()[0],n);o.on("fold",function(){o.refresh()});o.on("unfold",function(){o.refresh()})},s=function(){if(!t.results)return!1;if(!t.results.getOriginalResponseAsString)return!1;var e=t.results.getOriginalResponseAsString();return e&&0!=e.length||!t.results.getException()?!0:!1},l=function(){if(!t.results)return null;var e=t.results.getOriginalContentType(),n=t.results.getType();return{getContent:function(){return t.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:e?e:"text/plain",buttonTitle:"Download raw response"}};return{draw:a,name:"Raw Response",canHandleResults:s,getPriority:2,getDownloadInfo:l}};i.defaults={CodeMirror:{readOnly:!0,lineNumbers:!0,lineWrapping:!0,foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"]}};i.version={"YASR-rawResponse":t("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":27,codemirror:10,"codemirror/addon/edit/matchbrackets.js":5,"codemirror/addon/fold/brace-fold.js":6,"codemirror/addon/fold/foldcode.js":7,"codemirror/addon/fold/foldgutter.js":8,"codemirror/addon/fold/xml-fold.js":9,"codemirror/mode/javascript/javascript.js":11,"codemirror/mode/xml/xml.js":12,jquery:18}],44:[function(t,e){"use strict";var n=t("jquery"),r=t("yasgui-utils"),i=t("./imgs.js");t("../lib/DataTables/media/js/jquery.dataTables.js");var o=e.exports=function(e){var a=null,s={name:"Table",getPriority:10},u=s.options=n.extend(!0,{},o.defaults),c=u.persistency?e.getPersistencyId(u.persistency.tableLength):null,f=function(){var t=[],n=e.results.getBindings(),r=e.results.getVariables(),i=null;e.options.getUsedPrefixes&&(i="function"==typeof e.options.getUsedPrefixes?e.options.getUsedPrefixes(e):e.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var a=[];a.push("");for(var l=n[o],c=0;c<r.length;c++){var f=r[c];a.push(f in l?u.getCellContent?u.getCellContent(e,s,l,f,{rowId:o,colId:c,usedPrefixes:i}):"":"")}t.push(a)}return t},h=function(){a.on("order.dt",function(){d()});c&&a.on("length.dt",function(t,e,n){r.storage.set(c,n,"month")});n.extend(!0,u.callbacks,u.handlers);a.delegate("td","click",function(t){if(u.callbacks&&u.callbacks.onCellClick){var e=u.callbacks.onCellClick(this,t);if(e===!1)return!1}}).delegate("td","mouseenter",function(t){u.callbacks&&u.callbacks.onCellMouseEnter&&u.callbacks.onCellMouseEnter(this,t);var e=n(this);u.fetchTitlesFromPreflabel&&void 0===e.attr("title")&&0==e.text().trim().indexOf("http")&&l(e)}).delegate("td","mouseleave",function(t){u.callbacks&&u.callbacks.onCellMouseLeave&&u.callbacks.onCellMouseLeave(this,t)})};s.draw=function(){a=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>');n(e.resultsContainer).html(a);var t=u.datatable;t.data=f();t.columns=u.getColumns(e,s);var i=r.storage.get(c);i&&(t.pageLength=i);a.DataTable(n.extend(!0,{},t));d();h();var o=e.header.outerHeight()-5;o>0&&e.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+o+"px").css("margin-bottom","-"+o+"px")};var d=function(){var t={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};a.find(".sortIcons").remove();var e=8,o=13;for(var s in t){var l=n("<div class='sortIcons'></div>").css("float","right").css("margin-right","-12px").width(e).height(o);r.svg.draw(l,i[t[s]]);a.find("th."+s).append(l)}};s.canHandleResults=function(){return e.results&&e.results.getVariables&&e.results.getVariables()&&e.results.getVariables().length>0};s.getDownloadInfo=function(){return e.results?{getContent:function(){return t("./bindingsToCsv.js")(e.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return s},a=function(t,e,n){var r=n.value;if(n["xml:lang"])r='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var i="http://www.w3.org/2001/XMLSchema#",o=n.datatype;o=0==o.indexOf(i)?"xsd:"+o.substring(i.length):"<"+o+">";r='"'+r+'"^^'+o}return r},s=function(t,e,n,r,i){var o=n[r],s=null;if("uri"==o.type){var l=null,u=o.value,c=u;if(i.usedPrefixes)for(var f in i.usedPrefixes)if(0==c.indexOf(i.usedPrefixes[f])){c=f+":"+u.substring(i.usedPrefixes[f].length);break}if(e.options.mergeLabelsWithUris){var h="string"==typeof e.options.mergeLabelsWithUris?e.options.mergeLabelsWithUris:"Label";if(n[r+h]){c=a(t,e,n[r+h]);l=u}}s="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+c+"</a>"}else s="<span class='nonUri'>"+a(t,e,o)+"</span>";return s},l=function(t){var e=function(){t.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(t.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?t.attr("title",n.label):"string"==typeof n&&n.length>0?t.attr("title",n):e()}).fail(e)};o.defaults={getCellContent:s,persistency:{tableLength:"tableLength"},getColumns:function(t,e){var n=function(n){if(!e.options.mergeLabelsWithUris)return!0;var r="string"==typeof e.options.mergeLabelsWithUris?e.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&t.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];r.push({title:""});t.results.getVariables().forEach(function(t){r.push({title:t,visible:n(t)})});return r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!1,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(t){for(var e=0;e<t.aiDisplay.length;e++)n("td:eq(0)",t.aoData[t.aiDisplay[e]].nTr).html(e+1);var r=!1;n(t.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)});r?n(t.nTableWrapper).find(".dataTables_paginate").show():n(t.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"12px",orderable:!1,targets:0}]}};o.version={"YASR-table":t("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/DataTables/media/js/jquery.dataTables.js":2,"../package.json":27,"./bindingsToCsv.js":28,"./imgs.js":34,jquery:18,"yasgui-utils":24}],45:[function(t,e){"use strict";t("jquery");e.exports={uriToPrefixed:function(t,e){if(t)for(var n in t)if(0==e.indexOf(t[n])){e=n+":"+e.substring(t[n].length);break}return e},getGoogleType:function(t){if(null==t.type||"typed-literal"!==t.type&&"literal"!==t.type)return"string";switch(t.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return"number";case"http://www.w3.org/2001/XMLSchema#date":return"date";case"http://www.w3.org/2001/XMLSchema#dateTime":return"datetime";case"http://www.w3.org/2001/XMLSchema#time":return"timeofday";default:return"string"}},castGoogleType:function(t,n){if(null==t)return null;if(null==t.type||"typed-literal"!==t.type&&"literal"!==t.type)return(t.type="uri")?e.exports.uriToPrefixed(n,t.value):t.value;switch(t.datatype){case"http://www.w3.org/2001/XMLSchema#float":case"http://www.w3.org/2001/XMLSchema#decimal":case"http://www.w3.org/2001/XMLSchema#int":case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#long":case"http://www.w3.org/2001/XMLSchema#gYearMonth":case"http://www.w3.org/2001/XMLSchema#gYear":case"http://www.w3.org/2001/XMLSchema#gMonthDay":case"http://www.w3.org/2001/XMLSchema#gDay":case"http://www.w3.org/2001/XMLSchema#gMonth":return Number(t.value);case"http://www.w3.org/2001/XMLSchema#date":case"http://www.w3.org/2001/XMLSchema#dateTime":case"http://www.w3.org/2001/XMLSchema#time":return new Date(t.value);default:return t.value}}}},{jquery:18}]},{},[1])(1)}); //# sourceMappingURL=yasr.bundled.min.js.map
config/index.js
bradparks/react-redux-starter-kit
process.env.NODE_ENV = process.env.NODE_ENV || 'development'; const resolve = require('path').resolve, yargs = require('yargs').argv, _slice = [].slice; const SRC_DIRNAME = 'src', DIST_DIRNAME = 'dist', PROJECT_PATH = resolve(__dirname, '../'); function inProject () { return resolve.apply(resolve, [PROJECT_PATH].concat(_slice.apply(arguments))); } module.exports = exports = { // environment NODE_ENV : process.env.NODE_ENV, __DEBUG__ : !!yargs.debug, __DEV__ : process.env.NODE_ENV === 'development', __PROD__ : process.env.NODE_ENV === 'production', // path helpers SRC_DIRNAME : SRC_DIRNAME, DIST_DIRNAME : DIST_DIRNAME, PROJECT_PATH : PROJECT_PATH, inProject : inProject, inSrc : inProject.bind(undefined, SRC_DIRNAME), inDist : inProject.bind(undefined, DIST_DIRNAME), // build system // these will be bundled separately from the core app VENDOR_DEPENDENCIES : [ 'immutable', 'react', 'react-redux', 'react-router', 'redux' ], // server configuration WEBPACK_PORT : 3000, SERVER_PORT : process.env.PORT || 4000 };
ajax/libs/rxjs/2.2.2/rx.js
ppavlov/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. (function (window, undefined) { var freeExports = typeof exports == 'object' && exports, freeModule = typeof module == 'object' && module && module.exports == freeExports && module, freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal) { window = freeGlobal; } /** * @name Rx * @type Object */ var Rx = { Internals: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = Date.now; function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } // 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); } } /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** `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; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } 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; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.Internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { var result; // 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 && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // 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 || (!suportNodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor, ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { 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 length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; 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) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; // 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; } } return result; } // deep compare each object for(var key in b) { if (hasOwnProperty.call(b, key)) { // count properties and deep compare each property value size++; return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB)); } } if (result) { // ensure both objects have the same number of properties for (var key in 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; /** @private */ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ 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)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (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) { if (index === undefined) { 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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * 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 }; /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. * * @constructor */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype; /** * Gets the underlying disposable. After disposal, the result of getting this method is undefined. * @returns {Disposable} The underlying disposable. */ SingleAssignmentDisposablePrototype.getDisposable = function () { return this.current; }; /* @private */ SingleAssignmentDisposable.disposable = function (value) { return arguments.length ? this.getDisposable() : this.setDisposable(value); }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ SingleAssignmentDisposablePrototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; if (!shouldDispose) { this.current = value; } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable. */ SingleAssignmentDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. * @constructor */ var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; var serialDisposablePrototype = SerialDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ serialDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ serialDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /* @private */ serialDisposablePrototype.disposable = function (value) { if (!value) { return this.getDisposable(); } else { this.setDisposable(value); } }; /** * Disposes the underlying disposable as well as all future replacements. */ serialDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * 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; })(); /** * @constructor * @private */ function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false; } /** * @private * @memberOf ScheduledDisposable# */ ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; 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 () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } 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 invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * 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.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * 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). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { 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). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = window.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { window.clearInterval(id); }); }; /** * 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); }; /** * 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 }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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'); }); }; /** 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) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); 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 schedulerNoBlockError = 'Scheduler is not allowed to block the thread'; /** * 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) { if (dueTime > 0) throw new Error(schedulerNoBlockError); 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 Trampoline() { queue = new PriorityQueue(4); } Trampoline.prototype.dispose = function () { queue = null; }; Trampoline.prototype.run = function () { var item; while (queue.length > 0) { item = queue.dequeue(); if (!item.isCancelled()) { 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), t; if (!queue) { t = new Trampoline(); try { queue.enqueue(si); t.run(); } catch (e) { throw e; } finally { t.dispose(); } } 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 === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { function postMessageSupported () { // Ensure not in a worker if (!window.postMessage || window.importScripts) { return false; } var isAsync = false, oldHandler = window.onmessage; // Test for async window.onmessage = function () { isAsync = true; }; window.postMessage('','*'); window.onmessage = oldHandler; return isAsync; } // Check for setImmediate first for Node v0.11+ if (typeof window.setImmediate === 'function') { scheduleMethod = window.setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } 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 (window.addEventListener) { window.addEventListener('message', onGlobalPostMessage, false); } else { window.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; window.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!window.MessageChannel) { var channel = new window.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 window && 'onreadystatechange' in window.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = window.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; window.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return window.setTimeout(action, 0); }; clearMethod = window.clearTimeout; } }()); /** * 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 = window.setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { window.clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * 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. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @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. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (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 (exception) { var notification = new Notification('E'); notification.exception = exception; 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; }; }()); /** * @constructor * @private */ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { this.moveNext = moveNext; this.getCurrent = getCurrent; this.dispose = dispose; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { var done = false; dispose || (dispose = noop); return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; dispose(); } return result; }, function () { return getCurrent(); }, function () { if (!done) { dispose(); done = true; } }); }; /** @private */ var Enumerable = Rx.Internals.Enumerable = (function () { /** * @constructor * @private */ function Enumerable(getEnumerator) { this.getEnumerator = getEnumerator; } /** * @private * @memberOf Enumerable# */ Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } else { e.dispose(); } } catch (exception) { ex = exception; e.dispose(); } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; e.dispose(); })); }); }; /** * @private * @memberOf Enumerable# */ Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext; hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (exception) { ex = exception; } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; return Enumerable; }()); /** * @static * @private * @memberOf Enumerable */ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount === undefined) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; /** * @static * @private * @memberOf Enumerable */ var enumerableFor = Enumerable.forEach = function (source, selector) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector(source[index], index); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(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.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @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. * * @memberOf AbstractObserver * @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. * * @constructor * @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. * * @memberOf AnonymousObserver * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * * @memberOf AnonymousObserver * @param {Any{ error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. * * @memberOf AnonymousObserver */ 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; 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)); /** @private */ 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(); } /** @private */ ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; /** @private */ ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; /** @private */ ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; /** @private */ 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(); })); } }; /** @private */ ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return 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)); }); }; /** * 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; }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * * @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 = function (subscribe) { return new AnonymousObservable(function (o) { return disposableCreate(subscribe(o)); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ 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. * @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); } 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) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { 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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * 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); * @static * @memberOf Observable * @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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); 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). * * @static * @memberOf Observable * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * 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); * @static * @memberOf Observable * @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) { 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); * @static * @memberOf Observable * @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) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @static * @memberOf Observable * @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 = function (value, scheduler) { 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 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @static * @memberOf Observable * @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 = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @static * @memberOf Observable * @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(); if (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 that reacts first. * * @memberOf Observable# * @param {Observable} rightSource Second observable sequence. * @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(); 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 that reacts first. * * @example * E.g. winner = Rx.Observable.amb(xs, ys, zs); * @static * @memberOf Observable * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); 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 (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; } 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); }) * @memberOf Observable# * @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.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences 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; }); * @memberOf Observable# * @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 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; }); * @static * @memberOf Observable * @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) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(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]); * @memberOf Observable# * @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. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * * @memberOf Observable# * @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); * @memberOf Observable# * @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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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]); * * @static * @memberOf Observable * @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. * * @memberOf Observable# * @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); innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @memberOf Observable * @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]); * @static * @memberOf Observable * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); 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++]; d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { 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. * * @memberOf Observable# * @param {Observable} other The observable sequence 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) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); 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. * * @memberOf Observable# * @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); d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * * @memberOf Observable# * @param {Observable} other Observable sequence 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) { 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); * @memberOf Observable# * @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; }); var next = function (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) { 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); } 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. * * @static * @memberOf Observable * @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. * * @static * @memberOf Observable * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = slice.call(arguments); 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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * 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 (skip === undefined) { 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 (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 res = var obs = observable.distinctUntilChanged(); * var res = var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * 3 - var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @memberOf Observable# * @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. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * 3 - observable.doAction(onNext, onError); * 4 - observable.doAction(onNext, onError, onCompleted); * * @memberOf Observable# * @param {Mixed} 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 = 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 (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = obs = observable.finallyAction(function () { console.log('sequence ended'; }); * * @memberOf Observable# * @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 = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * * @memberOf Observable# * @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. * * @memberOf Observable# * @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 (exception) { observer.onNext(notificationCreateOnError(exception)); 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); * * @memberOf Observable# * @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. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * * @memberOf Observable# * @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. * * var res = scanned = source.scan(function (acc, x) { return acc + x; }); * var res = scanned = source.scan(0, function (acc, x) { return acc + x; }); * * @memberOf Observable# * @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 seed, hasSeed = false, accumulator; if (arguments.length === 2) { seed = arguments[0]; accumulator = arguments[1]; hasSeed = true; } else { accumulator = arguments[0]; } var source = this; return observableDefer(function () { var hasAccumulation = false, accumulation; return source.select(function (x) { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } return accumulation; }); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * * @memberOf Observable# * @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); if (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. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = obs = source.takeLast(5); * var res = obs = source.takeLast(5, Rx.Scheduler.timeout); * * @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. * * @memberOf Observable# * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * 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. * * @memberOf Observable# * @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 (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * 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); * * @memberOf Observable# * @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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (skip == null) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * 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 (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * * @memberOf Observable# * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * * @memberOf Observable# * @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 (exception) { observer.onError(exception); 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. * * @memberOf Observable# * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(selector).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 selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. * @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.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x) { return selector(x).select(function (y) { return resultSelector(x, y); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(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 = 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 observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.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; }); * * @memberOf Observable# * @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; } } if (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); * 2 - source.take(0, Rx.Scheduler.timeout); * * @memberOf Observable# * @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 Error(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) { remaining--; observer.onNext(x); if (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. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * * @memberOf Observable# * @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; }); * * @memberOf Observable# * @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 (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(subscribe(autoDetachObserver)); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } 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 GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @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; var hv = this.hasValue; var 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 () { 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) { var os = this.observers.slice(0); this.isStopped = true; var v = this.value; var 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 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 = []; } }, /** * 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) { 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)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); // Check for AMD if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.Rx = Rx; return define(function () { return Rx; }); } else if (freeExports) { if (typeof module == 'object' && module && module.exports == freeExports) { module.exports = Rx; } else { freeExports = Rx; } } else { window.Rx = Rx; } }(this));
src/js/components/icons/base/DocumentImage.js
odedre/grommet-final
/** * @description DocumentImage SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L19.9999998,23 M18,1 L18,6 L23,6 M3,11 L16,11 L16,23 L3,23 L3,11 Z M7,16 C7.55228475,16 8,15.5522847 8,15 C8,14.4477153 7.55228475,14 7,14 C6.44771525,14 6,14.4477153 6,15 C6,15.5522847 6.44771525,16 7,16 Z M5,23 L7,20 L9,22 L13,16 L16,20"/></svg> */ // (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}-document-image`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-image'); 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="none" stroke="#000" strokeWidth="2" d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L19.9999998,23 M18,1 L18,6 L23,6 M3,11 L16,11 L16,23 L3,23 L3,11 Z M7,16 C7.55228475,16 8,15.5522847 8,15 C8,14.4477153 7.55228475,14 7,14 C6.44771525,14 6,14.4477153 6,15 C6,15.5522847 6.44771525,16 7,16 Z M5,23 L7,20 L9,22 L13,16 L16,20"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentImage'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
ajax/libs/clappr/0.0.78/clappr.js
wallin/cdnjs
require=(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 (global){ "use strict"; var Player = require('./components/player'); var IframePlayer = require('./components/iframe_player'); var Mediator = require('mediator'); var version = require('../package.json').version; global.DEBUG = false; window.Clappr = { Player: Player, Mediator: Mediator, IframePlayer: IframePlayer }; window.Clappr.version = version; module.exports = window.Clappr; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../package.json":6,"./components/iframe_player":17,"./components/player":21,"mediator":"mediator"}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],3:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function checkObjectCoercible(argument) { if (argument == null) { throw new TypeError('Value cannot be converted to an Object'); } return argument; } function setupGlobals(global) { global.Symbol = Symbol; global.Reflect = global.Reflect || {}; global.Reflect.global = global.Reflect.global || global; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, isObject: isObject, toProperty: toProperty, type: types, typeof: typeOf, checkObjectCoercible: checkObjectCoercible, hasOwnProperty: function(o, p) { return hasOwnProperty.call(o, p); }, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; function spread() { var rv = [], j = 0, iterResult; for (var i = 0; i < arguments.length; i++) { var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]); if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') { throw new TypeError('Cannot spread non-iterable object.'); } var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)](); while (!(iterResult = iter.next()).done) { rv[j++] = iterResult.value; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; throw new $TypeError('super prototype must be an Object or null'); } if (superClass === null) return null; throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + ".")); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw x; case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime, canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) { this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName; if (!(cause instanceof $ModuleEvaluationError) && cause.stack) this.stack = this.stripStack(cause.stack); else this.stack = ''; }; var $ModuleEvaluationError = ModuleEvaluationError; ($traceurRuntime.createClass)(ModuleEvaluationError, { stripError: function(message) { return message.replace(/.*Error:/, this.constructor.name + ':'); }, stripCause: function(cause) { if (!cause) return ''; if (!cause.message) return cause + ''; return this.stripError(cause.message); }, loadedBy: function(moduleName) { this.stack += '\n loaded by ' + moduleName; }, stripStack: function(causeStack) { var stack = []; causeStack.split('\n').some((function(frame) { if (/UncoatedModuleInstantiator/.test(frame)) return true; stack.push(frame); })); stack[0] = this.stripError(stack[0]); return stack.join('\n'); } }, {}, Error); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; try { return this.value_ = this.func.call(global); } catch (ex) { if (ex instanceof ModuleEvaluationError) { ex.loadedBy(this.url); throw ex; } throw new ModuleEvaluationError(this.url, ex); } }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/utils"; var $ceil = Math.ceil; var $floor = Math.floor; var $isFinite = isFinite; var $isNaN = isNaN; var $pow = Math.pow; var $min = Math.min; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x >>> 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function isNumber(x) { return typeof x === 'number'; } function toInteger(x) { x = +x; if ($isNaN(x)) return 0; if (x === 0 || !$isFinite(x)) return x; return x > 0 ? $floor(x) : $ceil(x); } var MAX_SAFE_LENGTH = $pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH); } function checkIterable(x) { return !isObject(x) ? undefined : x[Symbol.iterator]; } function isConstructor(x) { return isCallable(x); } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function maybeDefine(object, name, descr) { if (!(name in object)) { Object.defineProperty(object, name, descr); } } function maybeDefineMethod(object, name, value) { maybeDefine(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } function maybeDefineConst(object, name, value) { maybeDefine(object, name, { value: value, configurable: false, enumerable: false, writable: false }); } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function maybeAddConsts(object, consts) { for (var i = 0; i < consts.length; i += 2) { var name = consts[i]; var value = consts[i + 1]; maybeDefineConst(object, name, value); } } function maybeAddIterator(object, func, Symbol) { if (!Symbol || !Symbol.iterator || object[Symbol.iterator]) return; if (object['@@iterator']) func = object['@@iterator']; Object.defineProperty(object, Symbol.iterator, { value: func, configurable: true, enumerable: false, writable: true }); } var polyfills = []; function registerPolyfill(func) { polyfills.push(func); } function polyfillAll(global) { polyfills.forEach((function(f) { return f(global); })); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get isNumber() { return isNumber; }, get toInteger() { return toInteger; }, get toLength() { return toLength; }, get checkIterable() { return checkIterable; }, get isConstructor() { return isConstructor; }, get createIteratorResultObject() { return createIteratorResultObject; }, get maybeDefine() { return maybeDefine; }, get maybeDefineMethod() { return maybeDefineMethod; }, get maybeDefineConst() { return maybeDefineConst; }, get maybeAddFunctions() { return maybeAddFunctions; }, get maybeAddConsts() { return maybeAddConsts; }, get maybeAddIterator() { return maybeAddIterator; }, get registerPolyfill() { return registerPolyfill; }, get polyfillAll() { return polyfillAll; } }; }); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Map"; var $__3 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), isObject = $__3.isObject, maybeAddIterator = $__3.maybeAddIterator, registerPolyfill = $__3.registerPolyfill; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError('Map called on incompatible type'); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError('Map can not be reentrantly initialised'); } initMap(this); if (iterable !== null && iterable !== undefined) { for (var $__5 = iterable[Symbol.iterator](), $__6; !($__6 = $__5.next()).done; ) { var $__7 = $__6.value, key = $__7[0], value = $__7[1]; { this.set(key, value); } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; return true; } return false; }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0; i < this.entries_.length; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } }, entries: $traceurRuntime.initGeneratorFunction(function $__8() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return [key, value]; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__8, this); }), keys: $traceurRuntime.initGeneratorFunction(function $__9() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return key; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__9, this); }), values: $traceurRuntime.initGeneratorFunction(function $__10() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return value; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__10, this); }) }, {}); Object.defineProperty(Map.prototype, Symbol.iterator, { configurable: true, writable: true, value: Map.prototype.entries }); function polyfillMap(global) { var $__7 = global, Object = $__7.Object, Symbol = $__7.Symbol; if (!global.Map) global.Map = Map; var mapPrototype = global.Map.prototype; if (mapPrototype.entries) { maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol); maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() { return this; }, Symbol); } } registerPolyfill(polyfillMap); return { get Map() { return Map; }, get polyfillMap() { return polyfillMap; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Map" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Set", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Set"; var $__11 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), isObject = $__11.isObject, maybeAddIterator = $__11.maybeAddIterator, registerPolyfill = $__11.registerPolyfill; var Map = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Map").Map; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; function initSet(set) { set.map_ = new Map(); } var Set = function Set() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError('Set called on incompatible type'); if ($hasOwnProperty.call(this, 'map_')) { throw new TypeError('Set can not be reentrantly initialised'); } initSet(this); if (iterable !== null && iterable !== undefined) { for (var $__15 = iterable[Symbol.iterator](), $__16; !($__16 = $__15.next()).done; ) { var item = $__16.value; { this.add(item); } } } }; ($traceurRuntime.createClass)(Set, { get size() { return this.map_.size; }, has: function(key) { return this.map_.has(key); }, add: function(key) { this.map_.set(key, key); return this; }, delete: function(key) { return this.map_.delete(key); }, clear: function() { return this.map_.clear(); }, forEach: function(callbackFn) { var thisArg = arguments[1]; var $__13 = this; return this.map_.forEach((function(value, key) { callbackFn.call(thisArg, key, key, $__13); })); }, values: $traceurRuntime.initGeneratorFunction(function $__18() { var $__19, $__20; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: $__19 = this.map_.keys()[Symbol.iterator](); $ctx.sent = void 0; $ctx.action = 'next'; $ctx.state = 12; break; case 12: $__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow); $ctx.state = 9; break; case 9: $ctx.state = ($__20.done) ? 3 : 2; break; case 3: $ctx.sent = $__20.value; $ctx.state = -2; break; case 2: $ctx.state = 12; return $__20.value; default: return $ctx.end(); } }, $__18, this); }), entries: $traceurRuntime.initGeneratorFunction(function $__21() { var $__22, $__23; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: $__22 = this.map_.entries()[Symbol.iterator](); $ctx.sent = void 0; $ctx.action = 'next'; $ctx.state = 12; break; case 12: $__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow); $ctx.state = 9; break; case 9: $ctx.state = ($__23.done) ? 3 : 2; break; case 3: $ctx.sent = $__23.value; $ctx.state = -2; break; case 2: $ctx.state = 12; return $__23.value; default: return $ctx.end(); } }, $__21, this); }) }, {}); Object.defineProperty(Set.prototype, Symbol.iterator, { configurable: true, writable: true, value: Set.prototype.values }); Object.defineProperty(Set.prototype, 'keys', { configurable: true, writable: true, value: Set.prototype.values }); function polyfillSet(global) { var $__17 = global, Object = $__17.Object, Symbol = $__17.Symbol; if (!global.Set) global.Set = Set; var setPrototype = global.Set.prototype; if (setPrototype.values) { maybeAddIterator(setPrototype, setPrototype.values, Symbol); maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() { return this; }, Symbol); } } registerPolyfill(polyfillSet); return { get Set() { return Set; }, get polyfillSet() { return polyfillSet; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Set" + ''); System.register("traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap"; var len = 0; function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { scheduleFlush(); } } var $__default = asap; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; 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 useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function() { channel.port2.postMessage(0); }; } function useSetTimeout() { return function() { setTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } var scheduleFlush; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Promise"; var async = System.get("traceur-runtime@0.0.62/node_modules/rsvp/lib/rsvp/asap").default; var registerPolyfill = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils").registerPolyfill; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { if (isPromise(x)) { return x; } return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } registerPolyfill(polyfillPromise); return { get Promise() { return Promise; }, get polyfillPromise() { return polyfillPromise; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Promise" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator", [], function() { "use strict"; var $__29; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator"; var $__27 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), createIteratorResultObject = $__27.createIteratorResultObject, isObject = $__27.isObject; var $__30 = $traceurRuntime, hasOwnProperty = $__30.hasOwnProperty, toProperty = $__30.toProperty; var iteratedString = Symbol('iteratedString'); var stringIteratorNextIndex = Symbol('stringIteratorNextIndex'); var StringIterator = function StringIterator() {}; ($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, "next", { value: function() { var o = this; if (!isObject(o) || !hasOwnProperty(o, iteratedString)) { throw new TypeError('this must be a StringIterator object'); } var s = o[toProperty(iteratedString)]; if (s === undefined) { return createIteratorResultObject(undefined, true); } var position = o[toProperty(stringIteratorNextIndex)]; var len = s.length; if (position >= len) { o[toProperty(iteratedString)] = undefined; return createIteratorResultObject(undefined, true); } var first = s.charCodeAt(position); var resultString; if (first < 0xD800 || first > 0xDBFF || position + 1 === len) { resultString = String.fromCharCode(first); } else { var second = s.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) { resultString = String.fromCharCode(first); } else { resultString = String.fromCharCode(first) + String.fromCharCode(second); } } o[toProperty(stringIteratorNextIndex)] = position + resultString.length; return createIteratorResultObject(resultString, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__29, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__29), {}); function createStringIterator(string) { var s = String(string); var iterator = Object.create(StringIterator.prototype); iterator[toProperty(iteratedString)] = s; iterator[toProperty(stringIteratorNextIndex)] = 0; return iterator; } return {get createStringIterator() { return createStringIterator; }}; }); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/String"; var createStringIterator = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/StringIterator").createStringIterator; var $__32 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), maybeAddFunctions = $__32.maybeAddFunctions, maybeAddIterator = $__32.maybeAddIterator, registerPolyfill = $__32.registerPolyfill; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } function stringPrototypeIterator() { var o = $traceurRuntime.checkObjectCoercible(this); var s = String(o); return createStringIterator(s); } function polyfillString(global) { var String = global.String; maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol); } registerPolyfill(polyfillString); return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; }, get stringPrototypeIterator() { return stringPrototypeIterator; }, get polyfillString() { return polyfillString; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/String" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__36; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator"; var $__34 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), toObject = $__34.toObject, toUint32 = $__34.toUint32, createIteratorResultObject = $__34.createIteratorResultObject; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__36, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__36), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Array"; var $__37 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/ArrayIterator"), entries = $__37.entries, keys = $__37.keys, values = $__37.values; var $__38 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), checkIterable = $__38.checkIterable, isCallable = $__38.isCallable, isConstructor = $__38.isConstructor, maybeAddFunctions = $__38.maybeAddFunctions, maybeAddIterator = $__38.maybeAddIterator, registerPolyfill = $__38.registerPolyfill, toInteger = $__38.toInteger, toLength = $__38.toLength, toObject = $__38.toObject; function from(arrLike) { var mapFn = arguments[1]; var thisArg = arguments[2]; var C = this; var items = toObject(arrLike); var mapping = mapFn !== undefined; var k = 0; var arr, len; if (mapping && !isCallable(mapFn)) { throw TypeError(); } if (checkIterable(items)) { arr = isConstructor(C) ? new C() : []; for (var $__39 = items[Symbol.iterator](), $__40; !($__40 = $__39.next()).done; ) { var item = $__40.value; { if (mapping) { arr[k] = mapFn.call(thisArg, item, k); } else { arr[k] = item; } k++; } } arr.length = k; return arr; } len = toLength(items.length); arr = isConstructor(C) ? new C(len) : new Array(len); for (; k < len; k++) { if (mapping) { arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k); } else { arr[k] = items[k]; } } arr.length = len; return arr; } function of() { for (var items = [], $__41 = 0; $__41 < arguments.length; $__41++) items[$__41] = arguments[$__41]; var C = this; var len = items.length; var arr = isConstructor(C) ? new C(len) : new Array(len); for (var k = 0; k < len; k++) { arr[k] = items[k]; } arr.length = len; return arr; } function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } function polyfillArray(global) { var $__42 = global, Array = $__42.Array, Object = $__42.Object, Symbol = $__42.Symbol; maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); maybeAddFunctions(Array, ['from', from, 'of', of]); maybeAddIterator(Array.prototype, values, Symbol); maybeAddIterator(Object.getPrototypeOf([].values()), function() { return this; }, Symbol); } registerPolyfill(polyfillArray); return { get from() { return from; }, get of() { return of; }, get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; }, get polyfillArray() { return polyfillArray; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Array" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Object"; var $__43 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), maybeAddFunctions = $__43.maybeAddFunctions, registerPolyfill = $__43.registerPolyfill; var $__44 = $traceurRuntime, defineProperty = $__44.defineProperty, getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor, getOwnPropertyNames = $__44.getOwnPropertyNames, keys = $__44.keys, privateNames = $__44.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } function polyfillObject(global) { var Object = global.Object; maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } registerPolyfill(polyfillObject); return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; }, get polyfillObject() { return polyfillObject; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Object" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/Number", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/Number"; var $__46 = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils"), isNumber = $__46.isNumber, maybeAddConsts = $__46.maybeAddConsts, maybeAddFunctions = $__46.maybeAddFunctions, registerPolyfill = $__46.registerPolyfill, toInteger = $__46.toInteger; var $abs = Math.abs; var $isFinite = isFinite; var $isNaN = isNaN; var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1; var EPSILON = Math.pow(2, -52); function NumberIsFinite(number) { return isNumber(number) && $isFinite(number); } ; function isInteger(number) { return NumberIsFinite(number) && toInteger(number) === number; } function NumberIsNaN(number) { return isNumber(number) && $isNaN(number); } ; function isSafeInteger(number) { if (NumberIsFinite(number)) { var integral = toInteger(number); if (integral === number) return $abs(integral) <= MAX_SAFE_INTEGER; } return false; } function polyfillNumber(global) { var Number = global.Number; maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]); maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]); } registerPolyfill(polyfillNumber); return { get MAX_SAFE_INTEGER() { return MAX_SAFE_INTEGER; }, get MIN_SAFE_INTEGER() { return MIN_SAFE_INTEGER; }, get EPSILON() { return EPSILON; }, get isFinite() { return NumberIsFinite; }, get isInteger() { return isInteger; }, get isNaN() { return NumberIsNaN; }, get isSafeInteger() { return isSafeInteger; }, get polyfillNumber() { return polyfillNumber; } }; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/Number" + ''); System.register("traceur-runtime@0.0.62/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.62/src/runtime/polyfills/polyfills"; var polyfillAll = System.get("traceur-runtime@0.0.62/src/runtime/polyfills/utils").polyfillAll; polyfillAll(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfillAll(global); }; return {}; }); System.get("traceur-runtime@0.0.62/src/runtime/polyfills/polyfills" + ''); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":2}],4:[function(require,module,exports){ /*global define:false */ /** * Copyright 2013 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.4.6 * @url craig.is/killing/mice */ (function(window, document, undefined) { /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc', 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _directMap = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequenceLevels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _resetTimer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignoreNextKeyup = false, /** * temporary state where we will ignore the next keypress * * @type {boolean} */ _ignoreNextKeypress = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _nextExpectedAction = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { object.addEventListener(type, callback, false); return; } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { var character = String.fromCharCode(e.which); // if the shift key is not pressed then it is safe to assume // that we want the character to be lowercase. this means if // you accidentally have caps lock on then your key bindings // will continue to work // // the only side effect that might not be desired is if you // bind something like 'A' cause you want to trigger an // event when capital A is pressed caps lock will no longer // trigger the event. shift+a will though. if (!e.shiftKey) { character = character.toLowerCase(); } return character; } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map // with keydown and keyup events the character seems to always // come in as an uppercase character whether you are pressing shift // or not. we should make sure it is always lowercase for comparisons return String.fromCharCode(e.which).toLowerCase(); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} doNotReset * @returns void */ function _resetSequences(doNotReset) { doNotReset = doNotReset || {}; var activeSequences = false, key; for (key in _sequenceLevels) { if (doNotReset[key]) { activeSequences = true; continue; } _sequenceLevels[key] = 0; } if (!activeSequences) { _nextExpectedAction = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {Event|Object} e * @param {string=} sequenceName - name of the sequence we are looking for * @param {string=} combination * @param {number=} level * @returns {Array} */ function _getMatches(character, modifiers, e, sequenceName, combination, level) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // when you bind a combination or sequence a second time it // should overwrite the first one. if a sequenceName or // combination is specified in this call it does just that // // @todo make deleting its own method? var deleteCombo = !sequenceName && callback.combo == combination; var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; if (deleteCombo || deleteSequence) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * prevents default for this event * * @param {Event} e * @returns void */ function _preventDefault(e) { if (e.preventDefault) { e.preventDefault(); return; } e.returnValue = false; } /** * stops propogation for this event * * @param {Event} e * @returns void */ function _stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); return; } e.cancelBubble = true; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e, combo, sequence) { // if this event should not happen stop here if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) { return; } if (callback(e, combo) === false) { _preventDefault(e); _stopPropagation(e); } } /** * handles a character key event * * @param {string} character * @param {Array} modifiers * @param {Event} e * @returns void */ function _handleKey(character, modifiers, e) { var callbacks = _getMatches(character, modifiers, e), i, doNotReset = {}, maxLevel = 0, processedSequenceCallback = false; // Calculate the maxLevel for sequences so we can only execute the longest callback sequence for (i = 0; i < callbacks.length; ++i) { if (callbacks[i].seq) { maxLevel = Math.max(maxLevel, callbacks[i].level); } } // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { // only fire callbacks for the maxLevel to prevent // subsequences from also firing // // for example 'a option b' should not cause 'option b' to fire // even though 'option b' is part of the other sequence // // any sequences that do not match here will be discarded // below by the _resetSequences call if (callbacks[i].level != maxLevel) { continue; } processedSequenceCallback = true; // keep a list of which sequences were matches for later doNotReset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processedSequenceCallback) { _fireCallback(callbacks[i].callback, e, callbacks[i].combo); } } // if the key you pressed matches the type of sequence without // being a modifier (ie "keyup" or "keypress") then we should // reset all sequences that were not matched by this event // // this is so, for example, if you have the sequence "h a t" and you // type "h e a r t" it does not match. in this case the "e" will // cause the sequence to reset // // modifier keys are ignored because you can have a sequence // that contains modifiers such as "enter ctrl+space" and in most // cases the modifier key will be pressed before the next key // // also if you have a sequence such as "ctrl+b a" then pressing the // "b" key will trigger a "keypress" and a "keydown" // // the "keydown" is expected when there is a modifier, but the // "keypress" ends up matching the _nextExpectedAction since it occurs // after and that causes the sequence to reset // // we ignore keypresses in a sequence that directly follow a keydown // for the same character var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress; if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) { _resetSequences(doNotReset); } _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown'; } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKeyEvent(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion if (typeof e.which !== 'number') { e.which = e.keyCode; } var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } // need to use === for the character check because the character can be 0 if (e.type == 'keyup' && _ignoreNextKeyup === character) { _ignoreNextKeyup = false; return; } Mousetrap.handleKey(character, _eventModifiers(e), e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_resetTimer); _resetTimer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequenceLevels[combo] = 0; /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {string} nextAction * @returns {Function} */ function _increaseSequence(nextAction) { return function() { _nextExpectedAction = nextAction; ++_sequenceLevels[combo]; _resetSequenceTimer(); }; } /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ function _callbackAndReset(e) { _fireCallback(callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); } // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences // // if an action is specified in the original bind call then that will // be used throughout. otherwise we will pass the action that the // next key in the sequence should match. this allows a sequence // to mix and match keypress and keydown events depending on which // ones are better suited to the key provided for (var i = 0; i < keys.length; ++i) { var isFinal = i + 1 === keys.length; var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action); _bindSingle(keys[i], wrappedCallback, action, combo, i); } } /** * Converts from a string key combination to an array * * @param {string} combination like "command+shift+l" * @return {Array} */ function _keysFromString(combination) { if (combination === '+') { return ['+']; } return combination.split('+'); } /** * Gets info for a specific key combination * * @param {string} combination key combination ("command+s" or "a" or "*") * @param {string=} action * @returns {Object} */ function _getKeyInfo(combination, action) { var keys, key, i, modifiers = []; // take the keys from this pattern and figure out what the actual // pattern is all about keys = _keysFromString(combination); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); return { key: key, modifiers: modifiers, action: action }; } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequenceName - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequenceName, level) { // store a direct mapped reference for use with Mousetrap.trigger _directMap[combination + ':' + action] = callback; // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), info; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { _bindSequence(combination, sequence, callback, action); return; } info = _getKeyInfo(combination, action); // make sure to initialize array if this is the first time // a callback is added for this key _callbacks[info.key] = _callbacks[info.key] || []; // remove an existing match if there is one _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[info.key][sequenceName ? 'unshift' : 'push']({ callback: callback, modifiers: info.modifiers, action: info.action, seq: sequenceName, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKeyEvent); _addEvent(document, 'keydown', _handleKeyEvent); _addEvent(document, 'keyup', _handleKeyEvent); var Mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * an array of keys, or a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { keys = keys instanceof Array ? keys : [keys]; _bindMultiple(keys, callback, action); return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _directMap dict. * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { return Mousetrap.bind(keys, function() {}, action); }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { if (_directMap[keys + ':' + action]) { _directMap[keys + ':' + action]({}, keys); } return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _directMap = {}; return this; }, /** * should we stop this event before firing off callbacks * * @param {Event} e * @param {Element} element * @return {boolean} */ stopCallback: function(e, element) { // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; }, /** * exposes _handleKey publicly so it can be overwritten by extensions */ handleKey: _handleKey }; // expose mousetrap to the global object window.Mousetrap = Mousetrap; // expose mousetrap as an AMD module if (typeof define === 'function' && define.amd) { define(Mousetrap); } }) (window, document); },{}],5:[function(require,module,exports){ (function( factory ) { if (typeof define !== 'undefined' && define.amd) { define([], factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(); } else { window.scrollMonitor = factory(); } })(function() { var scrollTop = function() { return window.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop; }; var exports = {}; var watchers = []; var VISIBILITYCHANGE = 'visibilityChange'; var ENTERVIEWPORT = 'enterViewport'; var FULLYENTERVIEWPORT = 'fullyEnterViewport'; var EXITVIEWPORT = 'exitViewport'; var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport'; var LOCATIONCHANGE = 'locationChange'; var STATECHANGE = 'stateChange'; var eventTypes = [ VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE ]; var defaultOffsets = {top: 0, bottom: 0}; var getViewportHeight = function() { return window.innerHeight || document.documentElement.clientHeight; }; var getDocumentHeight = function() { // jQuery approach // whichever is greatest return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight ); }; exports.viewportTop = null; exports.viewportBottom = null; exports.documentHeight = null; exports.viewportHeight = getViewportHeight(); var previousDocumentHeight; var latestEvent; var calculateViewportI; function calculateViewport() { exports.viewportTop = scrollTop(); exports.viewportBottom = exports.viewportTop + exports.viewportHeight; exports.documentHeight = getDocumentHeight(); if (exports.documentHeight !== previousDocumentHeight) { calculateViewportI = watchers.length; while( calculateViewportI-- ) { watchers[calculateViewportI].recalculateLocation(); } previousDocumentHeight = exports.documentHeight; } } function recalculateWatchLocationsAndTrigger() { exports.viewportHeight = getViewportHeight(); calculateViewport(); updateAndTriggerWatchers(); } var recalculateAndTriggerTimer; function debouncedRecalcuateAndTrigger() { clearTimeout(recalculateAndTriggerTimer); recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 ); } var updateAndTriggerWatchersI; function updateAndTriggerWatchers() { // update all watchers then trigger the events so one can rely on another being up to date. updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].update(); } updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].triggerCallbacks(); } } function ElementWatcher( watchItem, offsets ) { var self = this; this.watchItem = watchItem; if (!offsets) { this.offsets = defaultOffsets; } else if (offsets === +offsets) { this.offsets = {top: offsets, bottom: offsets}; } else { this.offsets = { top: offsets.top || defaultOffsets.top, bottom: offsets.bottom || defaultOffsets.bottom }; } this.callbacks = {}; // {callback: function, isOne: true } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport; var wasFullyInViewport; var wasAboveViewport; var wasBelowViewport; var listenerToTriggerListI; var listener; function triggerCallbackArray( listeners ) { if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while( listenerToTriggerListI-- ) { listener = listeners[listenerToTriggerListI]; listener.callback.call( self, latestEvent ); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks() { if (this.isInViewport && !wasInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); } if (this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); } switch( true ) { case wasInViewport !== this.isInViewport: case wasFullyInViewport !== this.isFullyInViewport: case wasAboveViewport !== this.isAboveViewport: case wasBelowViewport !== this.isBelowViewport: triggerCallbackArray( this.callbacks[STATECHANGE] ); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function() { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var boundingRect = this.watchItem.getBoundingClientRect(); this.top = boundingRect.top + exports.viewportTop; this.bottom = boundingRect.bottom + exports.viewportTop; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = exports.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray( this.callbacks[LOCATIONCHANGE] ); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } ElementWatcher.prototype = { on: function( event, callback, isOne ) { // trigger the event if it applies to the element right now. switch( true ) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport: callback.call( this, latestEvent ); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({callback: callback, isOne: isOne||false}); } else { throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, off: function( event, callback ) { if (this.callbacks[event]) { for (var i = 0, item; item = this.callbacks[event][i]; i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, one: function( event, callback ) { this.on( event, callback, true); }, recalculateSize: function() { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; }, update: function() { this.isAboveViewport = this.top < exports.viewportTop; this.isBelowViewport = this.bottom > exports.viewportBottom; this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop); this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); }, destroy: function() { var index = watchers.indexOf(this), self = this; watchers.splice(index, 1); for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]].length = 0; } }, // prevent recalculating the element location lock: function() { this.locked = true; }, unlock: function() { this.locked = false; } }; var eventHandlerFactory = function (type) { return function( callback, isOne ) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; ElementWatcher.prototype[type] = eventHandlerFactory(type); } try { calculateViewport(); } catch (e) { try { window.$(calculateViewport); } catch (e) { throw new Error('If you must put scrollMonitor in the <head>, you must use jQuery.'); } } function scrollMonitorListener(event) { latestEvent = event; calculateViewport(); updateAndTriggerWatchers(); } if (window.addEventListener) { window.addEventListener('scroll', scrollMonitorListener); window.addEventListener('resize', debouncedRecalcuateAndTrigger); } else { // Old IE support window.attachEvent('onscroll', scrollMonitorListener); window.attachEvent('onresize', debouncedRecalcuateAndTrigger); } exports.beget = exports.create = function( element, offsets ) { if (typeof element === 'string') { element = document.querySelector(element); } else if (element && element.length > 0) { element = element[0]; } var watcher = new ElementWatcher( element, offsets ); watchers.push(watcher); watcher.update(); return watcher; }; exports.update = function() { latestEvent = null; calculateViewport(); updateAndTriggerWatchers(); }; exports.recalculateLocations = function() { exports.documentHeight = 0; exports.update(); }; return exports; }); },{}],6:[function(require,module,exports){ module.exports={ "name": "clappr", "version": "0.0.78", "description": "An extensible media player for the web", "main": "dist/clappr.min.js", "scripts": { "test": "./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox" }, "repository": { "type": "git", "url": "git@github.com:globocom/clappr.git" }, "author": "Globo.com", "license": "BSD", "bugs": { "url": "https://github.com/globocom/clappr/issues" }, "browser": { "zepto": "clappr-zepto" }, "homepage": "https://github.com/globocom/clappr", "devDependencies": { "browserify": "^8.0.3", "chai": "1.10.0", "compass-mixins": "0.12.3", "dotenv": "^0.4.0", "es6ify": "~1.4.0", "exorcist": "^0.1.6", "express": "^4.6.1", "express-alias": "0.4.0", "glob": "^4.0.2", "gulp": "^3.8.1", "clappr-zepto": "0.0.3", "gulp-compressor": "^0.1.0", "gulp-jshint": "1.9.0", "gulp-livereload": "^2.1.0", "gulp-minify-css": "~0.3.5", "gulp-rename": "^1.2.0", "gulp-sass": "1.0.0", "gulp-streamify": "0.0.5", "gulp-uglify": "^1.0.1", "gulp-util": "3.0.1", "karma": "^0.12.17", "karma-browserify": "^1.0.0", "karma-chai": "^0.1.0", "karma-chrome-launcher": "^0.1.4", "karma-cli": "0.0.4", "karma-firefox-launcher": "^0.1.3", "karma-jasmine": "^0.2.2", "karma-jquery": "^0.1.0", "karma-mocha": "^0.1.4", "karma-safari-launcher": "^0.1.1", "karma-sinon": "^1.0.3", "karma-sinon-chai": "^0.2.0", "mkdirp": "^0.5.0", "s3": "^4.1.1", "scp": "0.0.3", "sinon": "^1.10.2", "traceur": "0.0.72", "vinyl-source-stream": "^1.0.0", "vinyl-transform": "0.0.1", "watchify": "^2.0.0", "yargs": "1.3.3" }, "dependencies": { "underscore": "1.7.0", "mousetrap": "^1.4.6", "scrollmonitor": "^1.0.8" } } },{}],7:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %><div class="bar-container" data-<%= name %>><% for (var i = 0; i < segments; i++) { %><div class="segmented-bar-element" data-<%= name %>></div><% } %></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'), 'seek_time': _.template('<span data-seek-time></span>'), 'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'), 'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'), 'background_button': _.template('<div class="background-button-wrapper" data-background-button><button class="background-button-icon" data-background-button></button></div>'), 'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'), 'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}', 'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}', 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}', 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}', 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'html_img': '[data-html-img]{max-width:100%;max-height:100%}', 'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}', 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}', 'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,"Open Sans",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,"Open Sans",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:"|";margin-right:7px}', 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":"underscore"}],8:[function(require,module,exports){ "use strict"; var $ = require('zepto'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style class="clappr-style"></style>').html(_.template(JST.CSS[name])(options))[0]; }}; module.exports = Styler; },{"./jst":7,"underscore":"underscore","zepto":"zepto"}],9:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var Browser = require('browser'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var formatTime = function(time) { time = time * 1000; time = parseInt(time / 1000); var seconds = time % 60; time = parseInt(time / 60); var minutes = time % 60; time = parseInt(time / 60); var hours = time % 24; var out = ""; if (hours && hours > 0) out += ("0" + hours).slice(-2) + ":"; out += ("0" + minutes).slice(-2) + ":"; out += ("0" + seconds).slice(-2); return out.trim(); }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; var Config = function Config() {}; ($traceurRuntime.createClass)(Config, {}, { _defaultConfig: function() { return {volume: { value: 100, parse: parseInt }}; }, _defaultValueFor: function(key) { try { return this._defaultConfig()[key]['parse'](this._defaultConfig()[key]['value']); } catch (e) { return undefined; } }, _create_keyspace: function(key) { return 'clappr.' + document.domain + '.' + key; }, restore: function(key) { if (Browser.hasLocalstorage && localStorage[this._create_keyspace(key)]) { return this._defaultConfig()[key]['parse'](localStorage[this._create_keyspace(key)]); } return this._defaultValueFor(key); }, persist: function(key, value) { if (Browser.hasLocalstorage) { try { localStorage[this._create_keyspace(key)] = value; return true; } catch (e) { return false; } } } }); var seekStringToSeconds = function(url) { var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse(); var seconds = 0; var factor = 1; _.each(elements, function(el) { seconds += (parseInt(el) * factor); factor = factor * 60; }, this); return seconds; }; module.exports = { extend: extend, formatTime: formatTime, Fullscreen: Fullscreen, Config: Config, seekStringToSeconds: seekStringToSeconds }; },{"browser":"browser","underscore":"underscore"}],10:[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Events = require('events'); var Container = function Container(options) { $traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]); this.playback = options.playback; this.settings = this.playback.settings; this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; this.bindEvents(); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return { class: 'container', 'data-container': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress); this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated); this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready); this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering); this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull); this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate); this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata); this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate); this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate); this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged); this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged); this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl); this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl); this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended); this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing); this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger(Events.CONTAINER_PLAYBACKSTATE); }, playbackDvrStateChanged: function(dvrInUse) { this.settings = this.playback.settings; this.dvrInUse = dvrInUse; this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse); }, updateBitrate: function(newBitrate) { this.trigger(Events.CONTAINER_BITRATE, newBitrate); }, statsReport: function(metrics) { this.trigger(Events.CONTAINER_STATS_REPORT, metrics); }, getPlaybackType: function() { return this.playback.getPlaybackType(); }, isDvrEnabled: function() { return !!this.playback.dvrEnabled; }, isDvrInUse: function() { return !!this.dvrInUse; }, destroy: function() { this.trigger(Events.CONTAINER_DESTROYED, this, this.name); this.playback.destroy(); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger(Events.CONTAINER_READY, this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, getDuration: function() { return this.playback.getDuration(); }, error: function(errorObj) { this.$el.append(errorObj.render().el); this.trigger(Events.CONTAINER_ERROR, { error: errorObj, container: this }, this.name); }, loadedMetadata: function(duration) { this.trigger(Events.CONTAINER_LOADEDMETADATA, duration); }, timeUpdated: function(position, duration) { this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger(Events.CONTAINER_PLAY, this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger(Events.CONTAINER_STOP, this.name); this.playback.stop(); }, pause: function() { this.trigger(Events.CONTAINER_PAUSE, this.name); this.playback.pause(); }, ended: function() { this.trigger(Events.CONTAINER_ENDED, this, this.name); }, clicked: function() { this.trigger(Events.CONTAINER_CLICK, this, this.name); }, setCurrentTime: function(time) { this.trigger(Events.CONTAINER_SEEK, time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger(Events.CONTAINER_VOLUME, value, this.name); this.playback.volume(value); }, fullscreen: function() { this.trigger(Events.CONTAINER_FULLSCREEN, this.name); }, buffering: function() { this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name); }, bufferfull: function() { this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger(Events.CONTAINER_SETTINGSUPDATE); }, highDefinitionUpdate: function() { this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); module.exports = Container; },{"../../base/styler":8,"events":"events","ui_object":"ui_object","underscore":"underscore"}],11:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('base_object'); var Container = require('container'); var $ = require('zepto'); var Events = require('events'); var ContainerFactory = function ContainerFactory(options, loader) { $traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]); this.options = options; this.loader = loader; }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { createContainers: function() { var $__0 = this; return $.Deferred((function(promise) { promise.resolve(_.map($__0.options.sources, (function(source) { return $__0.createContainer(source); }), $__0)); })); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay(source.toString()); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var options = _.extend({}, this.options, { src: source, autoPlay: !!this.options.autoPlay }); var playback = new playbackPlugin(options); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, Events.CONTAINER_READY, (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(Plugin) { var options = _.extend(this.options, { container: container, src: source }); container.addPlugin(new Plugin(options)); }, this); } }, {}, BaseObject); module.exports = ContainerFactory; },{"base_object":"base_object","container":"container","events":"events","underscore":"underscore","zepto":"zepto"}],12:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":11}],13:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('zepto'); var UIObject = require('ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Styler = require('../../base/styler'); var MediaControl = require('media_control'); var PlayerInfo = require('player_info'); var Mediator = require('mediator'); var Events = require('events'); var Core = function Core(options) { var $__0 = this; $traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]); PlayerInfo.options = options; this.options = options; this.plugins = []; this.containers = []; this.createContainers(options); $(document).bind('fullscreenchange', (function() { return $__0.exit(); })); $(document).bind('MSFullscreenChange', (function() { return $__0.exit(); })); $(document).bind('mozfullscreenchange', (function() { return $__0.exit(); })); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, createContainers: function(options) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.containerFactory = new ContainerFactory(options, options.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.setFullscreen(); } else { this.setPlayerSize(); } Mediator.trigger(Events.PLAYER_RESIZE); }, setFullscreen: function() { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); PlayerInfo.previousSize = PlayerInfo.currentSize; PlayerInfo.currentSize = { width: $(window).width(), height: $(window).height() }; }, setPlayerSize: function() { this.$el.removeClass('fullscreen'); PlayerInfo.currentSize = PlayerInfo.previousSize; PlayerInfo.previousSize = { width: $(window).width(), height: $(window).height() }; this.resize(PlayerInfo.currentSize); }, resize: function(options) { var size = _.pick(options, 'width', 'height'); this.$el.css(size); PlayerInfo.previousSize = PlayerInfo.currentSize; PlayerInfo.currentSize = size; Mediator.trigger(Events.PLAYER_RESIZE); }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isArray(sources) ? sources : [sources.toString()]; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.options = _(this.options).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); this.mediaControl.destroy(); $(document).unbind('fullscreenchange'); $(document).unbind('MSFullscreenChange'); $(document).unbind('mozfullscreenchange'); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, Events.CONTAINER_DESTROYED, this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.options.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options)); this.listenTo(this.mediaControl, Events.MEDIACONTROL_FULLSCREEN, this.toggleFullscreen); this.listenTo(this.mediaControl, Events.MEDIACONTROL_SHOW, this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, Events.MEDIACONTROL_HIDE, this.onMediaControlShow.bind(this, false)); } }, createMediaControl: function(options) { if (options.mediacontrol && options.mediacontrol.external) { return new options.mediacontrol.external(options); } else { return new MediaControl(options); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.options.width = this.options.width || this.$el.width(); this.options.height = this.options.height || this.$el.height(); PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height'); this.updateSize(); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":8,"../../base/utils":9,"../container_factory":12,"events":"events","media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],14:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('base_object'); var Core = require('core'); var CoreFactory = function CoreFactory(player, loader) { this.player = player; this.options = player.options; this.loader = loader; this.options.loader = this.loader; }; ($traceurRuntime.createClass)(CoreFactory, { create: function() { this.core = new Core(this.options); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.corePlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }, {}, BaseObject); module.exports = CoreFactory; },{"base_object":"base_object","core":"core","underscore":"underscore"}],15:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":14}],16:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var $ = require('zepto'); var Player = require('../player'); var IframePlayer = function IframePlayer(options) { $traceurRuntime.superCall(this, $IframePlayer.prototype, "constructor", [options]); this.options = options; this.createIframe(); }; var $IframePlayer = IframePlayer; ($traceurRuntime.createClass)(IframePlayer, { createIframe: function() { this.iframe = document.createElement("iframe"); this.iframe.setAttribute("frameborder", 0); this.iframe.setAttribute("id", this.uniqueId); this.iframe.setAttribute("allowfullscreen", true); this.iframe.setAttribute("scrolling", "no"); this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString()); this.iframe.setAttribute('width', this.options.width); this.iframe.setAttribute('height', this.options.height); }, attachTo: function(element) { element.appendChild(this.iframe); }, addEventListeners: function() { var $__0 = this; this.iframe.contentWindow.addEventListener("fullscreenchange", (function() { return $__0.updateSize(); })); this.iframe.contentWindow.addEventListener("webkitfullscreenchange", (function() { return $__0.updateSize(); })); this.iframe.contentWindow.addEventListener("mozfullscreenchange", (function() { return $__0.updateSize(); })); }, buildQueryString: function() { var result = ""; for (var param in this.options) { result += !!result ? "&" : "?"; result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param]); } return result; } }, {}, BaseObject); module.exports = IframePlayer; },{"../player":21,"base_object":"base_object","zepto":"zepto"}],17:[function(require,module,exports){ "use strict"; module.exports = require('./iframe_player'); },{"./iframe_player":16}],18:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":19}],19:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var _ = require('underscore'); var PlayerInfo = require('player_info'); var HTML5VideoPlayback = require('html5_video'); var FlashVideoPlayback = require('flash'); var HTML5AudioPlayback = require('html5_audio'); var HLSVideoPlayback = require('hls'); var HTMLImgPlayback = require('html_img'); var NoOp = require('../../playbacks/no_op'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('poster'); var GoogleAnalyticsPlugin = require('../../plugins/google_analytics'); var ClickToPausePlugin = require('../../plugins/click_to_pause'); var BackgroundButton = require('../../plugins/background_button'); var DVRControls = require('../../plugins/dvr_controls'); var Loader = function Loader(externalPlugins) { $traceurRuntime.superCall(this, $Loader.prototype, "constructor", []); this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, HTMLImgPlayback, NoOp]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin]; this.corePlugins = [BackgroundButton, DVRControls]; if (externalPlugins) { this.addExternalPlugins(externalPlugins); } }; var $Loader = Loader; ($traceurRuntime.createClass)(Loader, { addExternalPlugins: function(plugins) { var pluginName = function(plugin) { return plugin.prototype.name; }; if (plugins.playback) { this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName); } if (plugins.container) { this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName); } if (plugins.core) { this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName); } PlayerInfo.playbackPlugins = this.playbackPlugins; }, getPlugin: function(name) { var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins); return _.find(allPlugins, function(plugin) { return plugin.prototype.name === name; }); } }, {}, BaseObject); module.exports = Loader; },{"../../playbacks/no_op":29,"../../plugins/background_button":32,"../../plugins/click_to_pause":34,"../../plugins/dvr_controls":36,"../../plugins/google_analytics":38,"../../plugins/spinner_three_bounce":42,"../../plugins/stats":44,"../../plugins/watermark":46,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","html_img":"html_img","player_info":"player_info","poster":"poster","underscore":"underscore"}],20:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('zepto'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('ui_object'); var Utils = require('../../base/utils'); var SeekTime = require('../seek_time'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var Events = require('events'); require('mousetrap'); var MediaControl = function MediaControl(options) { var $__0 = this; $traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]); this.seekTime = new SeekTime(this); this.options = options; this.mute = this.options.mute; this.persistConfig = this.options.persistConfig; this.container = options.container; var initialVolume = (this.persistConfig) ? Utils.Config.restore("volume") : 100; this.setVolume(this.mute ? 0 : initialVolume); this.keepVisible = false; this.addEventListeners(); this.settings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.disabled = false; if (this.container.mediaControlDisabled || this.options.chromeless) { this.disable(); } $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); Mediator.on(Events.PLAYER_RESIZE, (function() { return $__0.playerResize(); })); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click .bar-container[data-seekbar]': 'seek', 'click .bar-container[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseenter .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar', 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, addEventListeners: function() { this.listenTo(this.container, Events.CONTAINER_PLAY, this.changeTogglePlay); this.listenTo(this.container, Events.CONTAINER_TIMEUPDATE, this.updateSeekBar); this.listenTo(this.container, Events.CONTAINER_PROGRESS, this.updateProgressBar); this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate); this.listenTo(this.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate); this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate); this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_DISABLE, this.disable); this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_ENABLE, this.enable); this.listenTo(this.container, Events.CONTAINER_ENDED, this.ended); }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.options.chromeless) return; this.disabled = false; this.show(); }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); this.trigger(Events.MEDIACONTROL_PLAYING); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger(Events.MEDIACONTROL_NOTPLAYING); } }, mousemoveOnSeekBar: function(event) { if (this.container.settings.seekEnabled) { var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2); this.$seekBarHover.css({left: offsetX}); } this.trigger(Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, event); }, mouseleaveOnSeekBar: function(event) { this.trigger(Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, event); }, playerResize: function() { if (Utils.Fullscreen.isFullscreen()) { this.$fullscreenToggle.addClass('shrink'); } else { this.$fullscreenToggle.removeClass('shrink'); } this.$el.removeClass('w320'); if (PlayerInfo.currentSize.width <= 320) { this.$el.addClass('w320'); } }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { if (!this.container.settings.seekEnabled) return; this.draggingSeekBar = true; this.$el.addClass('dragging'); this.$seekBarLoaded.addClass('media-control-notransition'); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; this.$el.addClass('dragging'); if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.$el.removeClass('dragging'); this.$seekBarLoaded.removeClass('media-control-notransition'); this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition dragging'); this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageX - this.$volumeBarContainer.offset().left; var volumeFromUI = (offsetY / this.$volumeBarContainer.width()) * 100; this.setVolume(volumeFromUI); }, toggleMute: function() { if (this.mute) { if (this.currentVolume <= 0) { this.currentVolume = 100; } this.setVolume(this.currentVolume); } else { this.setVolume(0); } }, setVolume: function(value) { this.currentVolume = Math.min(100, Math.max(value, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); this.mute = this.currentVolume === 0; this.persistConfig && Utils.Config.persist("volume", this.currentVolume); }, toggleFullscreen: function() { this.trigger(Events.MEDIACONTROL_FULLSCREEN, this.name); this.container.fullscreen(); this.resetKeepVisible(); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.container.isDvrInUse()); this.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) { this.disable(); } this.trigger(Events.MEDIACONTROL_CONTAINERCHANGED); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; var timeout = 400; if (!this.$volumeBarContainer) return; if (this.draggingVolumeBar) { this.hideVolumeId = setTimeout((function() { return $__0.hideVolumeBar(); }), timeout); } else { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { return $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), timeout); } }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; if (position < 0) position = duration; this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { if (!this.container.settings.seekEnabled) return; var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); this.setSeekPercentage(pos); return false; }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, isVisible: function() { return !this.$el.hasClass('media-control-hide'); }, show: function(event) { var $__0 = this; if (this.disabled || this.container.getPlaybackType() === null) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { clearTimeout(this.hideId); this.$el.show(); this.trigger(Events.MEDIACONTROL_SHOW, this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; clearTimeout(this.hideId); if (!this.isVisible() || this.options.hideMediaControl === false) return; if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { this.trigger(Events.MEDIACONTROL_HIDE, this.name); this.$el.addClass('media-control-hide'); this.hideVolumeBar(); } }, settingsUpdate: function() { if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) { this.settings = this.container.settings; this.render(); this.enable(); } else { this.disable(); } }, highDefinitionUpdate: function() { if (this.container.isHighDefinitionInUse()) { this.$el.find('button[data-hd-indicator]').addClass("enabled"); } else { this.$el.find('button[data-hd-indicator]').removeClass("enabled"); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var $__0 = this; if (!this.container.isReady || !this.$volumeBarContainer) { this.listenToOnce(this.container, Events.CONTAINER_READY, (function() { return $__0.setVolumeLevel(value); })); } else { this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill'); var item = Math.ceil(value / 10.0); this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill'); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } } }, setSeekPercentage: function(value) { if (value > 100) return; var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0); this.currentSeekPercentage = value; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; Mousetrap.bind(['space'], (function() { return $__0.togglePlayPause(); })); }, unbindKeyEvents: function() { Mousetrap.unbind('space'); }, parseColors: function() { if (this.options.mediacontrol) { var buttonsColor = this.options.mediacontrol.buttons; var seekbarColor = this.options.mediacontrol.seekbar; this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor); this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor); this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', "inset 2px 0 0 " + buttonsColor); } }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); this.$el.html(this.template({settings: this.settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) { this.hide(); } this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (!this.currentSeekPercentage) { this.currentSeekPercentage = 0; } this.setSeekPercentage(this.currentSeekPercentage); this.$el.ready((function() { if (!$__0.container.settings.seekEnabled) { $__0.$seekBarContainer.addClass('seek-disabled'); } $__0.setVolume($__0.currentVolume); $__0.bindKeyEvents(); $__0.hideVolumeBar(); })); this.parseColors(); this.seekTime.render(); this.trigger(Events.MEDIACONTROL_RENDERED); return this; }, destroy: function() { $(document).unbind('mouseup'); $(document).unbind('mousemove'); this.unbindKeyEvents(); } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"../seek_time":22,"events":"events","mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],21:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var CoreFactory = require('./core_factory'); var Loader = require('./loader'); var _ = require('underscore'); var ScrollMonitor = require('scrollmonitor'); var PlayerInfo = require('player_info'); var Player = function Player(options) { $traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]); window.p = this; var defaultOptions = { persistConfig: true, width: 640, height: 360 }; this.options = _.extend(defaultOptions, options); this.options.sources = this.normalizeSources(options); this.loader = new Loader(this.options.plugins || {}); this.coreFactory = new CoreFactory(this, this.loader); PlayerInfo.currentSize = { width: options.width, height: options.height }; if (this.options.parentId) { this.setParentId(this.options.parentId); } }; var $Player = Player; ($traceurRuntime.createClass)(Player, { setParentId: function(parentId) { var el = document.querySelector(parentId); if (el) { this.attachTo(el); } }, attachTo: function(element) { this.options.parentElement = element; this.core = this.coreFactory.create(); if (this.options.autoPlayVisible) { this.bindAutoPlayVisible(this.options.autoPlayVisible); } }, bindAutoPlayVisible: function(option) { var $__0 = this; this.elementWatcher = ScrollMonitor.create(this.core.$el); if (option === 'full') { this.elementWatcher.fullyEnterViewport((function() { return $__0.enterViewport(); })); } else if (option === 'partial') { this.elementWatcher.enterViewport((function() { return $__0.enterViewport(); })); } }, enterViewport: function() { if (this.elementWatcher.top !== 0 && !this.isPlaying()) { this.play(); } }, normalizeSources: function(options) { var sources = _.compact(_.flatten([options.source, options.sources])); return _.isEmpty(sources) ? ['no.op'] : sources; }, resize: function(size) { this.core.resize(size); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); }, play: function() { this.core.mediaControl.container.play(); }, pause: function() { this.core.mediaControl.container.pause(); }, stop: function() { this.core.mediaControl.container.stop(); }, seek: function(time) { this.core.mediaControl.container.setCurrentTime(time); }, setVolume: function(volume) { this.core.mediaControl.container.setVolume(volume); }, mute: function() { this.core.mediaControl.container.setVolume(0); }, unmute: function() { this.core.mediaControl.container.setVolume(100); }, isPlaying: function() { return this.core.mediaControl.container.isPlaying(); } }, {}, BaseObject); module.exports = Player; },{"./core_factory":15,"./loader":18,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":"underscore"}],22:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":23}],23:[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var formatTime = require('../../base/utils').formatTime; var Events = require('events'); var SeekTime = function SeekTime(mediaControl) { $traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []); this.mediaControl = mediaControl; this.addEventListeners(); }; var $SeekTime = SeekTime; ($traceurRuntime.createClass)(SeekTime, { get name() { return 'seek_time'; }, get template() { return JST.seek_time; }, get attributes() { return { 'class': 'seek-time hidden', 'data-seek-time': '' }; }, addEventListeners: function() { this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, this.showTime); this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, this.hideTime); }, showTime: function(event) { var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left; var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0)); var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2); pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width()); var currentTime = timePosition * this.mediaControl.container.getDuration() / 100; var options = { timestamp: currentTime, formattedTime: formatTime(currentTime), pointerPosition: pointerPosition }; this.update(options); }, hideTime: function() { this.$el.addClass('hidden'); this.$el.css('left', '-100%'); }, update: function(options) { if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) { this.$el.find('[data-seek-time]').text(options.formattedTime); this.$el.css('left', options.pointerPosition); this.$el.removeClass('hidden'); } }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.mediaControl.$el.append(this.el); } }, {}, UIObject); module.exports = SeekTime; },{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"events":"events","ui_object":"ui_object"}],24:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('mediator'); var _ = require('underscore'); var $ = require('zepto'); var Browser = require('browser'); var seekStringToSeconds = require('../../base/utils').seekStringToSeconds; var Events = require('events'); require('mousetrap'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var Flash = function Flash(options) { $traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]); this.src = options.src; this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/"; this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "Player.swf"; this.autoPlay = options.autoPlay; this.settings = {default: ['seekbar']}; this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; this.isReady = false; this.addListeners(); }; var $Flash = Flash; ($traceurRuntime.createClass)(Flash, { get name() { return 'flash'; }, get tagName() { return 'object'; }, get template() { return JST.flash; }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; if (this.currentState === 'PLAYING') { this.firstPlay(); } else { this.currentState = "IDLE"; this.autoPlay && this.play(); } $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); this.trigger(Events.PLAYBACK_READY, this.name); }, getPlaybackType: function() { return 'vod'; }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash', ''); this.setElement($el[0]); }, isHighDefinitionInUse: function() { return false; }, updateTime: function() { this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.getPosition(), this.el.getDuration(), this.name); }, addListeners: function() { Mediator.on(this.uniqueId + ':progress', this.progress, this); Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this); Mediator.on(this.uniqueId + ':statechanged', this.checkState, this); Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this); _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.bind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, stopListening: function() { $traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); Mediator.off(this.uniqueId + ':flashready'); _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.unbind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, checkState: function() { if (this.currentState === "PAUSED") { return; } else if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") { this.trigger(Events.PLAYBACK_BUFFERING, this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger(Events.PLAYBACK_BUFFERFULL, this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger(Events.PLAYBACK_ENDED, this.name); this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger(Events.PLAYBACK_PROGRESS, 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name); } }, firstPlay: function() { var $__0 = this; this.currentState = "PLAYING"; if (this.el.playerPlay) { this.el.playerPlay(this.src); this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() { return $__0.checkInitialSeek(); })); } else { this.listenToOnce(this, EVENTS.PLAYBACK_READY, this.firstPlay); } }, checkInitialSeek: function() { var seekTime = seekStringToSeconds(window.location.href); this.seekSeconds(seekTime); }, play: function() { if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') { this.currentState = "PLAYING"; this.el.playerResume(); } else if (this.el.getState() !== 'PLAYING') { this.firstPlay(); } this.trigger(Events.PLAYBACK_PLAY, this.name); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.playerVolume(value); } else { this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() { return $__0.volume(value); })); } }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name); }, isPlaying: function() { return !!(this.isReady && this.currentState === "PLAYING"); }, getDuration: function() { return this.el.getDuration(); }, seek: function(seekBarValue) { var seekTo = this.el.getDuration() * (seekBarValue / 100); this.seekSeconds(seekTo); }, seekSeconds: function(seekTo) { this.el.playerSeek(seekTo); this.trigger(Events.PLAYBACK_TIMEUPDATE, seekTo, this.el.getDuration(), this.name); if (this.currentState === "PAUSED") { this.el.playerPause(); } }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } this.$el.append(style); return this; } }, {}, Playback); Flash.canPlay = function(resource) { if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) { return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/); } }; module.exports = Flash; },{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"browser":"browser","events":"events","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":"underscore","zepto":"zepto"}],25:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('mediator'); var Browser = require('browser'); var Events = require('events'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var HLS = function HLS(options) { $traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]); this.src = options.src; this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/"; this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "HLSPlayer.swf"; this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache; this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage; this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop"], default: ['seekbar'], right: ["fullscreen", "volume", "hd-indicator"], seekEnabled: false }; this.settings = _.extend({}, this.defaultSettings); this.playbackType = 'live'; this.addListeners(); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'class': 'hls-playback', 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':playbackstate', (function(state) { return $__0.setPlaybackState(state); })); Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) { return $__0.updateHighDefinition(isHD); })); Mediator.on(this.uniqueId + ':playbackerror', (function() { return $__0.flashPlaybackError(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); Mediator.off(this.uniqueId + ':playbackerror'); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger(Events.PLAYBACK_READY, this.name); this.currentState = "IDLE"; this.setFlashSettings(); this.autoPlay && this.play(); }, setFlashSettings: function() { this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache); this.el.globoPlayerCapLeveltoStage(this.capLevelToStage); this.el.globoPlayerSetmaxBufferLength(0); }, updateHighDefinition: function(isHD) { this.highDefinition = (isHD === "true"); this.trigger(Events.PLAYBACK_HIGHDEFINITIONUPDATE); this.trigger(Events.PLAYBACK_BITRATE, {'bitrate': this.getCurrentBitrate()}); }, updateTime: function() { var duration = this.getDuration(); var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration); var previousDVRStatus = this.dvrEnabled; var livePlayback = (this.playbackType === 'live'); this.dvrEnabled = (livePlayback && duration > 240); if (duration === 100 || livePlayback === undefined) { return; } if (this.dvrEnabled !== previousDVRStatus) { this.updateSettings(); this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name); } if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) { position = duration; } this.trigger(Events.PLAYBACK_TIMEUPDATE, position, duration, this.name); }, play: function() { if (this.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else if (this.currentState !== "PLAYING") { this.firstPlay(); } this.trigger(Events.PLAYBACK_PLAY, this.name); }, getPlaybackType: function() { return this.playbackType ? this.playbackType : null; }, getCurrentBitrate: function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinitionInUse: function() { return this.highDefinition; }, getLevels: function() { if (!this.levels || this.levels.length === 0) { this.levels = this.el.globoGetLevels(); } return this.levels; }, setPlaybackState: function(state) { var bufferLength = this.el.globoGetbufferLength(); if (state === "PLAYING_BUFFERING" && bufferLength < 1) { this.trigger(Events.PLAYBACK_BUFFERING, this.name); this.updateCurrentState(state); } else if (state === "PLAYING") { if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) { this.trigger(Events.PLAYBACK_BUFFERFULL, this.name); this.updateCurrentState(state); } } else if (state === "PAUSED") { this.updateCurrentState(state); } else if (state === "IDLE") { this.trigger(Events.PLAYBACK_ENDED, this.name); this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.globoGetDuration(), this.name); this.updateCurrentState(state); } this.lastBufferLength = bufferLength; }, updateCurrentState: function(state) { this.currentState = state; this.updatePlaybackType(); }, updatePlaybackType: function() { this.playbackType = this.el.globoGetType(); if (this.playbackType) { this.playbackType = this.playbackType.toLowerCase(); if (this.playbackType === 'vod') { this.startReportingProgress(); } else { this.stopReportingProgress(); } } this.trigger(Events.PLAYBACK_PLAYBACKSTATE); }, startReportingProgress: function() { if (!this.reportingProgress) { this.reportingProgress = true; Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded); } }, stopReportingProgress: function() { Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this); }, onFragmentLoaded: function() { var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength(); this.trigger(Events.PLAYBACK_PROGRESS, this.el.globoGetPosition(), buffered, this.getDuration(), this.name); }, firstPlay: function() { this.el.globoPlayerLoad(this.src); this.el.globoPlayerPlay(); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.globoPlayerVolume(value); } else { this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() { return $__0.volume(value); })); } }, pause: function() { if (this.playbackType !== 'live' || this.dvrEnabled) { this.el.globoPlayerPause(); if (this.playbackType === 'live' && this.dvrEnabled) { this.updateDvr(true); } } }, stop: function() { this.el.globoPlayerStop(); this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name); }, isPlaying: function() { if (this.currentState) { return !!(this.currentState.match(/playing/i)); } return false; }, getDuration: function() { var duration = this.el.globoGetDuration(); if (this.playbackType === 'live') { duration = duration - 10; } return duration; }, seek: function(time) { var duration = this.getDuration(); if (time > 0) { time = duration * time / 100; } if (this.playbackType === 'live') { var dvrInUse = (time >= 0 && duration - time > 5); if (!dvrInUse) { time = -1; } this.updateDvr(dvrInUse); } this.el.globoPlayerSeek(time); this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name); }, updateDvr: function(dvrInUse) { var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = dvrInUse; if (this.dvrInUse !== previousDvrInUse) { this.updateSettings(); this.trigger(Events.PLAYBACK_DVR, this.dvrInUse); this.trigger(Events.PLAYBACK_STATS_ADD, {'dvr': this.dvrInUse}); } }, flashPlaybackError: function() { this.trigger(Events.PLAYBACK_STOP); }, timeUpdate: function(time, duration) { this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrInUse) { this.settings.left = ["playpause", "position", "duration"]; this.settings.seekEnabled = true; } else if (this.dvrEnabled) { this.settings.left = ["playpause"]; this.settings.seekEnabled = true; } else { this.settings.seekEnabled = false; } }, setElement: function(element) { this.$el = element; this.el = element[0]; }, render: function() { var style = Styler.getStyleFor(this.name); if (Browser.isLegacyIE) { this.setupIE(); } else { this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isIE) { this.$('embed').remove(); } } this.el.id = this.cid; this.$el.append(style); return this; } }, {}, Playback); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8?/); }; module.exports = HLS; },{"../../base/jst":7,"../../base/styler":8,"browser":"browser","events":"events","mediator":"mediator","playback":"playback","underscore":"underscore"}],26:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Events = require('events'); var HTML5Audio = function HTML5Audio(params) { $traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]); this.el.src = params.src; this.settings = { left: ['playpause', 'position', 'duration'], right: ['fullscreen', 'volume'], default: ['seekbar'] }; this.render(); params.autoPlay && this.play(); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended', 'canplaythrough': 'bufferFull' }; }, bindEvents: function() { this.listenTo(this.container, Events.CONTAINER_PLAY, this.play); this.listenTo(this.container, Events.CONTAINER_PAUSE, this.pause); this.listenTo(this.container, Events.CONTAINER_SEEK, this.seek); this.listenTo(this.container, Events.CONTAINER_VOLUME, this.volume); this.listenTo(this.container, Events.CONTAINER_STOP, this.stop); }, getPlaybackType: function() { return "aod"; }, play: function() { this.el.play(); this.trigger(Events.PLAYBACK_PLAY); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger(Events.CONTAINER_TIMEUPDATE, 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, timeUpdated: function() { this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name); }, bufferFull: function() { this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name); this.trigger(Events.PLAYBACK_BUFFERFULL); }, render: function() { this.trigger(Events.PLAYBACK_READY, this.name); return this; } }, {}, Playback); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"events":"events","playback":"playback"}],27:[function(require,module,exports){ (function (process){ "use strict"; var Playback = require('playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Browser = require('browser'); var seekStringToSeconds = require('../../base/utils').seekStringToSeconds; var Events = require('events'); var _ = require('underscore'); require('mousetrap'); var HTML5Video = function HTML5Video(options) { $traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]); this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.firstBuffer = true; this.isHLS = (this.src.indexOf('m3u8') > -1); this.settings = {default: ['seekbar']}; if (this.isHLS && Browser.isSafari) { this.settings.left = ["playstop"]; this.settings.right = ["fullscreen", "volume"]; } else { this.el.preload = options.preload ? options.preload : 'metadata'; this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } this.bindEvents(); }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get tagName() { return 'video'; }, get template() { return JST.html5_video; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, bindEvents: function() { _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.bind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, loadedMetadata: function(e) { this.trigger(Events.PLAYBACK_LOADEDMETADATA, e.target.duration); this.trigger(Events.PLAYBACK_SETTINGSUPDATE); this.checkInitialSeek(); }, getPlaybackType: function() { return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'; }, isHighDefinitionInUse: function() { return false; }, play: function() { this.el.play(); this.trigger(Events.PLAYBACK_PLAY); if (this.isHLS) { this.trigger(Events.PLAYBACK_TIMEUPDATE, 1, 1, this.name); } }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger(Events.PLAYBACK_ENDED, this.name); this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger(Events.PLAYBACK_BUFFERING, this.name); } }, waiting: function() { if (this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger(Events.PLAYBACK_BUFFERING, this.name); } }, bufferFull: function() { if (this.options.poster && this.firstBuffer) { this.firstBuffer = false; if (!this.isPlaying()) { this.el.poster = this.options.poster; } } else { this.el.poster = ''; } this.trigger(Events.PLAYBACK_BUFFERFULL, this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.seekSeconds(time); }, seekSeconds: function(time) { this.el.currentTime = time; }, checkInitialSeek: function() { var seekTime = seekStringToSeconds(window.location.href); this.seekSeconds(seekTime); }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { if (this.getPlaybackType() !== 'live') { this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name); } }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger(Events.PLAYBACK_PROGRESS, this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, typeFor: function(src) { return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'; }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) })); this.$el.append(style); this.trigger(Events.PLAYBACK_READY, this.name); process.nextTick((function() { return $__0.options.autoPlay && $__0.play(); })); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { var mimetypes = { 'mp4': _.map(["avc1.42E01E", "avc1.58A01E", "avc1.4D401E", "avc1.64001E", "mp4v.20.8", "mp4v.20.240"], function(codec) { return 'video/mp4; codecs=' + codec + ', mp4a.40.2'; }), 'ogg': ['video/ogg; codecs="theora, vorbis"', 'video/ogg; codecs="dirac"', 'video/ogg; codecs="theora, speex"'], '3gpp': ['video/3gpp; codecs="mp4v.20.8, samr"'], 'webm': ['video/webm; codecs="vp8, vorbis"'], 'mkv': ['video/x-matroska; codecs="theora, vorbis"'], 'm3u8': ['application/x-mpegURL'] }; mimetypes['ogv'] = mimetypes['ogg']; mimetypes['3gp'] = mimetypes['3gpp']; var extension = resource.split('?')[0].match(/.*\.(.*)$/)[1]; if (_.has(mimetypes, extension)) { var v = document.createElement('video'); return !!_.find(mimetypes[extension], function(ext) { return !!v.canPlayType(ext).replace(/no/, ''); }); } return false; }; module.exports = HTML5Video; }).call(this,require('_process')) },{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"_process":2,"browser":"browser","events":"events","mousetrap":4,"playback":"playback","underscore":"underscore"}],28:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Events = require('events'); var HTMLImg = function HTMLImg(params) { $traceurRuntime.superCall(this, $HTMLImg.prototype, "constructor", [params]); this.el.src = params.src; setTimeout(function() { this.trigger(Events.PLAYBACK_BUFFERFULL, this.name); }.bind(this), 1); }; var $HTMLImg = HTMLImg; ($traceurRuntime.createClass)(HTMLImg, { get name() { return 'html_img'; }, get tagName() { return 'img'; }, get attributes() { return {'data-html-img': ''}; }, getPlaybackType: function() { return null; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.append(style); return this; } }, {}, Playback); HTMLImg.canPlay = function(resource) { return !!resource.match(/(.*).(png|jpg|jpeg|gif|bmp)/); }; module.exports = HTMLImg; },{"../../base/jst":7,"../../base/styler":8,"events":"events","playback":"playback"}],29:[function(require,module,exports){ "use strict"; module.exports = require('./no_op'); },{"./no_op":30}],30:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var NoOp = function NoOp(options) { $traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]); }; var $NoOp = NoOp; ($traceurRuntime.createClass)(NoOp, { get name() { return 'no_op'; }, get template() { return JST.no_op; }, get attributes() { return {'data-no-op': ''}; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); return this; } }, {}, Playback); NoOp.canPlay = (function(source) { return true; }); module.exports = NoOp; },{"../../base/jst":7,"../../base/styler":8,"playback":"playback"}],31:[function(require,module,exports){ (function (process){ "use strict"; var UICorePlugin = require('ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Events = require('events'); var Browser = require('browser'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var BackgroundButton = function BackgroundButton(core) { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $BackgroundButton = BackgroundButton; ($traceurRuntime.createClass)(BackgroundButton, { get template() { return JST.background_button; }, get name() { return 'background_button'; }, get attributes() { return { 'class': 'background-button', 'data-background-button': '' }; }, get events() { return {'click .background-button-icon': 'click'}; }, bindEvents: function() { this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERING, this.hide); this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERFULL, this.show); this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate); this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_SHOW, this.updateSize); this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_PLAYING, this.playing); this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_NOTPLAYING, this.notplaying); Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []); Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this); }, settingsUpdate: function() { this.stopListening(); if (this.shouldRender()) { this.render(); this.bindEvents(); if (this.core.mediaControl.container.isPlaying()) { this.playing(); } else { this.notplaying(); } } else { this.$el.remove(); this.$playPauseButton.show(); this.$playStopButton.show(); this.listenTo(this.core.mediaControl.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate); this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate); this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.settingsUpdate); } }, shouldRender: function() { var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton; return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0); }, click: function() { this.core.mediaControl.show(); if (this.shouldStop) { this.core.mediaControl.togglePlayStop(); } else { this.core.mediaControl.togglePlayPause(); } }, show: function() { this.$el.removeClass('hide'); }, hide: function() { this.$el.addClass('hide'); }, enable: function() { this.stopListening(); $traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []); this.settingsUpdate(); }, disable: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []); this.$playPauseButton.show(); this.$playStopButton.show(); }, playing: function() { this.$buttonIcon.removeClass('notplaying').addClass('playing'); }, notplaying: function() { this.$buttonIcon.removeClass('playing').addClass('notplaying'); }, getExternalInterface: function() {}, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)}); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]'); this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]'); this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]'); this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]'); this.shouldStop = this.$playStopButton.length > 0; this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]')); this.$el.click((function() { return $__0.click($__0.$el); })); process.nextTick((function() { return $__0.updateSize(); })); if (this.core.options.useBackgroundButton) { this.$playPauseButton.hide(); this.$playStopButton.hide(); } if (this.shouldStop) { this.$buttonIcon.addClass('playstop'); } if (this.core.mediaControl.isVisible()) { this.show(); } return this; } }, {}, UICorePlugin); module.exports = BackgroundButton; }).call(this,require('_process')) },{"../../base/jst":7,"../../base/styler":8,"_process":2,"browser":"browser","events":"events","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],32:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":31}],33:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var Events = require('events'); var ClickToPausePlugin = function ClickToPausePlugin() { $traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments); }; var $ClickToPausePlugin = ClickToPausePlugin; ($traceurRuntime.createClass)(ClickToPausePlugin, { get name() { return 'click_to_pause'; }, bindEvents: function() { this.listenTo(this.container, Events.CONTAINER_CLICK, this.click); this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate); }, click: function() { if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } } }, settingsUpdate: function() { this.container.$el.removeClass('pointer-enabled'); if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { this.container.$el.addClass('pointer-enabled'); } } }, {}, ContainerPlugin); module.exports = ClickToPausePlugin; },{"container_plugin":"container_plugin","events":"events"}],34:[function(require,module,exports){ "use strict"; module.exports = require('./click_to_pause'); },{"./click_to_pause":33}],35:[function(require,module,exports){ "use strict"; var UICorePlugin = require('ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Events = require('events'); var DVRControls = function DVRControls(core) { $traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $DVRControls = DVRControls; ($traceurRuntime.createClass)(DVRControls, { get template() { return JST.dvr_controls; }, get name() { return 'dvr_controls'; }, get events() { return {'click .live-button': 'click'}; }, get attributes() { return { 'class': 'dvr-controls', 'data-dvr-controls': '' }; }, bindEvents: function() { this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate); this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.dvrChanged); }, dvrChanged: function(dvrEnabled) { this.settingsUpdate(); this.core.mediaControl.$el.addClass('live'); if (dvrEnabled) { this.core.mediaControl.$el.addClass('dvr'); this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide(); } else { this.core.mediaControl.$el.removeClass('dvr'); } }, click: function() { if (!this.core.mediaControl.container.isPlaying()) { this.core.mediaControl.container.play(); } if (this.core.mediaControl.$el.hasClass('dvr')) { this.core.mediaControl.container.setCurrentTime(-1); } }, settingsUpdate: function() { var $__0 = this; this.stopListening(); if (this.shouldRender()) { this.render(); this.$el.click((function() { return $__0.click(); })); } this.bindEvents(); }, shouldRender: function() { var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls; return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live'; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); if (this.shouldRender()) { this.core.mediaControl.$el.addClass('live'); this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el); if (this.$duration) { this.$duration.remove(); } this.$duration = $('<span data-duration></span>'); this.core.mediaControl.seekTime.$el.append(this.$duration); } return this; } }, {}, UICorePlugin); module.exports = DVRControls; },{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_core_plugin":"ui_core_plugin"}],36:[function(require,module,exports){ "use strict"; module.exports = require('./dvr_controls'); },{"./dvr_controls":35}],37:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var Events = require('events'); var GoogleAnalytics = function GoogleAnalytics(options) { $traceurRuntime.superCall(this, $GoogleAnalytics.prototype, "constructor", [options]); if (options.gaAccount) { this.embedScript(); this.account = options.gaAccount; this.trackerName = options.gaTrackerName + "." || 'Clappr.'; this.currentHDState = undefined; } }; var $GoogleAnalytics = GoogleAnalytics; ($traceurRuntime.createClass)(GoogleAnalytics, { get name() { return 'google_analytics'; }, embedScript: function() { var $__0 = this; if (!window._gat) { var script = document.createElement('script'); script.setAttribute("type", "text/javascript"); script.setAttribute("async", "async"); script.setAttribute("src", "http://www.google-analytics.com/ga.js"); script.onload = (function() { return $__0.addEventListeners(); }); document.body.appendChild(script); } else { this.addEventListeners(); } }, addEventListeners: function() { var $__0 = this; this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay); this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop); this.listenTo(this.container, Events.CONTAINER_PAUSE, this.onPause); this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull); this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded); this.listenTo(this.container, Events.CONTAINER_ERROR, this.onError); this.listenTo(this.container, Events.CONTAINER_PLAYBACKSTATE, this.onPlaybackChanged); this.listenTo(this.container, Events.CONTAINER_VOLUME, (function(event) { return $__0.onVolumeChanged(event); })); this.listenTo(this.container, Events.CONTAINER_SEEK, (function(event) { return $__0.onSeek(event); })); this.listenTo(this.container, Events.CONTAINER_FULL_SCREEN, this.onFullscreen); this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.onHD); this.listenTo(this.container.playback, Events.PLAYBACK_DVR, this.onDVR); _gaq.push([this.trackerName + '_setAccount', this.account]); }, onPlay: function() { this.push(["Video", "Play", this.container.playback.src]); }, onStop: function() { this.push(["Video", "Stop", this.container.playback.src]); }, onEnded: function() { this.push(["Video", "Ended", this.container.playback.src]); }, onBuffering: function() { this.push(["Video", "Buffering", this.container.playback.src]); }, onBufferFull: function() { this.push(["Video", "Bufferfull", this.container.playback.src]); }, onError: function() { this.push(["Video", "Error", this.container.playback.src]); }, onHD: function() { var status = this.container.isHighDefinitionInUse() ? "ON" : "OFF"; if (status !== this.currentHDState) { this.currentHDState = status; this.push(["Video", "HD - " + status, this.container.playback.src]); } }, onPlaybackChanged: function() { var type = this.container.getPlaybackType(); if (type !== null) { this.push(["Video", "Playback Type - " + type, this.container.playback.src]); } }, onDVR: function() { var status = this.container.isHighDefinitionInUse(); this.push(["Interaction", "DVR - " + status, this.container.playback.src]); }, onPause: function() { this.push(["Video", "Pause", this.container.playback.src]); }, onSeek: function() { this.push(["Video", "Seek", this.container.playback.src]); }, onVolumeChanged: function() { this.push(["Interaction", "Volume", this.container.playback.src]); }, onFullscreen: function() { this.push(["Interaction", "Fullscreen", this.container.playback.src]); }, push: function(array) { var res = [this.trackerName + "_trackEvent"].concat(array); _gaq.push(res); } }, {}, ContainerPlugin); module.exports = GoogleAnalytics; },{"container_plugin":"container_plugin","events":"events"}],38:[function(require,module,exports){ "use strict"; module.exports = require('./google_analytics'); },{"./google_analytics":37}],39:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":40}],40:[function(require,module,exports){ "use strict"; var _ = require('underscore'); require('mousetrap'); var Log = function Log() { var $__0 = this; Mousetrap.bind(['ctrl+shift+d'], (function() { return $__0.onOff(); })); this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; }; ($traceurRuntime.createClass)(Log, { info: function(klass, message) { this.log(klass, 'info', message); }, warn: function(klass, message) { this.log(klass, 'warn', message); }, debug: function(klass, message) { this.log(klass, 'debug', message); }, onOff: function() { window.DEBUG = !window.DEBUG; if (window.DEBUG) { console.log('log enabled'); } else { console.log('log disabled'); } }, log: function(klass, level, message) { if (!window.DEBUG || _.contains(this.BLACKLIST, message)) return; var color; if (level === 'warn') { color = '#FF8000'; } else if (level === 'info') { color = '#006600'; } else if (level === 'error') { color = '#FF0000'; } console.log("%c [" + klass + "] [" + level + "] " + message, 'color: ' + color); } }, {}); Log.getInstance = function() { if (this._instance === undefined) { this._instance = new this(); } return this._instance; }; module.exports = Log; },{"mousetrap":4,"underscore":"underscore"}],41:[function(require,module,exports){ (function (process){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Events = require('events'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var $ = require('zepto'); var _ = require('underscore'); var PosterPlugin = function PosterPlugin(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]); this.options = options; _.defaults(this.options, {disableControlsOnPoster: true}); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } this.render(); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferfull); this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop); this.listenTo(this.container, Events.CONTAINER_ENDED, this.onStop); Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []); Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this); }, onBuffering: function() { this.hidePlayButton(); }, onBufferfull: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.$playButton.show(); this.updateSize(); }, clicked: function() { this.container.play(); return false; }, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); if (this.$playWrapper.is(':visible')) { this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)}); if (!this.options.hidePlayButton) { this.$playButton.show(); } } else { this.$playButton.hide(); } }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playButton = this.$el.find('.poster-icon'); this.$playWrapper = this.$el.find('.play-wrapper'); if (this.options.poster !== undefined) { var imgEl = $('<img data-poster class="poster-background"></img>'); imgEl.attr('src', this.options.poster); this.$el.prepend(imgEl); } this.container.$el.append(this.el); if (!!this.options.hidePlayButton) { this.hidePlayButton(); } process.nextTick((function() { return $__0.updateSize(); })); return this; } }, {}, UIContainerPlugin); module.exports = PosterPlugin; }).call(this,require('_process')) },{"../../base/jst":7,"../../base/styler":8,"_process":2,"events":"events","mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":"underscore","zepto":"zepto"}],42:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":43}],43:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Events = require('events'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST.spinner_three_bounce; this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull); this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop); this.render(); }; var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin; ($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, { get name() { return 'spinner'; }, get attributes() { return { 'data-spinner': '', 'class': 'spinner-three-bounce' }; }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.html(this.template()); var style = Styler.getStyleFor('spinner_three_bounce'); this.container.$el.append(style); this.container.$el.append(this.$el); this.$el.hide(); return this; } }, {}, UIContainerPlugin); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],44:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":45}],45:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var $ = require("zepto"); var Events = require('events'); var StatsPlugin = function StatsPlugin(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, bindEvents: function() { this.listenTo(this.container.playback, Events.PLAYBACK_PLAY, this.onPlay); this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop); this.listenTo(this.container, Events.CONTAINER_DESTROYED, this.onStop); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering); this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull); this.listenTo(this.container, Events.CONTAINER_STATS_ADD, this.onStatsAdd); this.listenTo(this.container, Events.CONTAINER_BITRATE, this.onStatsAdd); this.listenTo(this.container.playback, Events.PLAYBACK_STATS_ADD, this.onStatsAdd); }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); if (!this.intervalId) { this.intervalId = setInterval(this.report.bind(this), this.reportInterval); } }, onStop: function() { clearInterval(this.intervalId); this.intervalId = undefined; this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay && !!this.startupTimeInit) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else if (!!this.rebufferingTimeInit) { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { this.container.statsReport(this.getStats()); } }, {}, ContainerPlugin); module.exports = StatsPlugin; },{"container_plugin":"container_plugin","events":"events","zepto":"zepto"}],46:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":47}],47:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Events = require('events'); var WaterMarkPlugin = function WaterMarkPlugin(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; if (options.watermark) { this.imageUrl = options.watermark; this.render(); } else { this.$el.remove(); } }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, bindEvents: function() { this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay); this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIContainerPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],"base_object":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./utils":9,"events":"events","underscore":"underscore"}],"browser":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); var hasLocalstorage = function() { try { localStorage.setItem('clappr', 'clappr'); localStorage.removeItem('clappr'); return true; } catch (e) { return false; } }; Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i)); Browser.isIE11 = !!(navigator.userAgent.match(/trident.*rv:11/i)); Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent)); Browser.isWiiU = !!(/WiiU/i.test(navigator.userAgent)); Browser.isPS4 = !!(/PlayStation 4/i.test(navigator.userAgent)); Browser.hasLocalstorage = hasLocalstorage(); module.exports = Browser; },{}],"container_plugin":[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var ContainerPlugin = function ContainerPlugin(options) { $traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]); this.bindEvents(); }; var $ContainerPlugin = ContainerPlugin; ($traceurRuntime.createClass)(ContainerPlugin, { enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); }, bindEvents: function() {}, destroy: function() { this.stopListening(); } }, {}, BaseObject); module.exports = ContainerPlugin; },{"base_object":"base_object"}],"container":[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":10}],"core_plugin":[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var CorePlugin = function CorePlugin(core) { $traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]); this.core = core; }; var $CorePlugin = CorePlugin; ($traceurRuntime.createClass)(CorePlugin, { getExternalInterface: function() { return {}; }, destroy: function() {} }, {}, BaseObject); module.exports = CorePlugin; },{"base_object":"base_object"}],"core":[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":13}],"events":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log').getInstance(); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; Log.info(klass, name); if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); Events.PLAYER_RESIZE = 'player:resize'; Events.PLAYBACK_PROGRESS = 'playback:progress'; Events.PLAYBACK_TIMEUPDATE = 'playback:timeupdate'; Events.PLAYBACK_READY = 'playback:ready'; Events.PLAYBACK_BUFFERING = 'playback:buffering'; Events.PLAYBACK_BUFFERFULL = 'playback:bufferfull'; Events.PLAYBACK_SETTINGSUPDATE = 'playback:settingsupdate'; Events.PLAYBACK_LOADEDMETADATA = 'playback:loadedmetadata'; Events.PLAYBACK_HIGHDEFINITIONUPDATE = 'playback:highdefinitionupdate'; Events.PLAYBACK_BITRATE = 'playback:bitrate'; Events.PLAYBACK_PLAYBACKSTATE = 'playback:playbackstate'; Events.PLAYBACK_DVR = 'playback:dvr'; Events.PLAYBACK_MEDIACONTROL_DISABLE = 'playback:mediacontrol:disable'; Events.PLAYBACK_MEDIACONTROL_ENABLE = 'playback:mediacontrol:enable'; Events.PLAYBACK_ENDED = 'playback:ended'; Events.PLAYBACK_PLAY = 'playback:play'; Events.PLAYBACK_ERROR = 'playback:error'; Events.PLAYBACK_STATS_ADD = 'playback:stats:add'; Events.CONTAINER_PLAYBACKSTATE = 'container:playbackstate'; Events.CONTAINER_PLAYBACKDVRSTATECHANGED = 'container:dvr'; Events.CONTAINER_BITRATE = 'container:bitrate'; Events.CONTAINER_STATS_REPORT = 'container:stats:report'; Events.CONTAINER_DESTROYED = 'container:destroyed'; Events.CONTAINER_READY = 'container:ready'; Events.CONTAINER_ERROR = 'container:error'; Events.CONTAINER_LOADEDMETADATA = 'container:loadedmetadata'; Events.CONTAINER_TIMEUPDATE = 'container:timeupdate'; Events.CONTAINER_PROGRESS = 'container:progress'; Events.CONTAINER_PLAY = 'container:play'; Events.CONTAINER_STOP = 'container:stop'; Events.CONTAINER_PAUSE = 'container:pause'; Events.CONTAINER_ENDED = 'container:ended'; Events.CONTAINER_CLICK = 'container:click'; Events.CONTAINER_SEEK = 'container:seek'; Events.CONTAINER_VOLUME = 'container:volume'; Events.CONTAINER_FULLSCREEN = 'container:fullscreen'; Events.CONTAINER_STATE_BUFFERING = 'container:state:buffering'; Events.CONTAINER_STATE_BUFFERFULL = 'container:state:bufferfull'; Events.CONTAINER_SETTINGSUPDATE = 'container:settingsupdate'; Events.CONTAINER_HIGHDEFINITIONUPDATE = 'container:highdefinitionupdate'; Events.CONTAINER_MEDIACONTROL_DISABLE = 'container:mediacontrol:disable'; Events.CONTAINER_MEDIACONTROL_ENABLE = 'container:mediacontrol:enable'; Events.CONTAINER_STATS_ADD = 'container:stats:add'; Events.MEDIACONTROL_RENDERED = 'mediacontrol:rendered'; Events.MEDIACONTROL_FULLSCREEN = 'mediacontrol:fullscreen'; Events.MEDIACONTROL_SHOW = 'mediacontrol:show'; Events.MEDIACONTROL_HIDE = 'mediacontrol:hide'; Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR = 'mediacontrol:mousemove:seekbar'; Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR = 'mediacontrol:mouseleave:seekbar'; Events.MEDIACONTROL_PLAYING = 'mediacontrol:playing'; Events.MEDIACONTROL_NOTPLAYING = 'mediacontrol:notplaying'; Events.MEDIACONTROL_CONTAINERCHANGED = 'mediacontrol:containerchanged'; module.exports = Events; },{"../plugins/log":39,"underscore":"underscore"}],"flash":[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":24}],"hls":[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":25}],"html5_audio":[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":26}],"html5_video":[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":27}],"html_img":[function(require,module,exports){ "use strict"; module.exports = require('./html_img'); },{"./html_img":28}],"media_control":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":20}],"mediator":[function(require,module,exports){ "use strict"; var Events = require('events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"events":"events"}],"playback":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Playback = function Playback(options) { $traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]); this.settings = {}; }; var $Playback = Playback; ($traceurRuntime.createClass)(Playback, { play: function() {}, pause: function() {}, stop: function() {}, seek: function(time) {}, getDuration: function() { return 0; }, isPlaying: function() { return false; }, getPlaybackType: function() { return 'no_op'; }, isHighDefinitionInUse: function() { return false; }, volume: function(value) {}, destroy: function() { this.$el.remove(); } }, {}, UIObject); Playback.canPlay = (function(source) { return false; }); module.exports = Playback; },{"ui_object":"ui_object"}],"player_info":[function(require,module,exports){ "use strict"; var PlayerInfo = { options: {}, playbackPlugins: [], currentSize: { width: 0, height: 0 } }; module.exports = PlayerInfo; },{}],"poster":[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":41}],"ui_container_plugin":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var UIContainerPlugin = function UIContainerPlugin(options) { $traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]); this.enabled = true; this.bindEvents(); }; var $UIContainerPlugin = UIContainerPlugin; ($traceurRuntime.createClass)(UIContainerPlugin, { enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, bindEvents: function() {}, destroy: function() { this.remove(); } }, {}, UIObject); module.exports = UIContainerPlugin; },{"ui_object":"ui_object"}],"ui_core_plugin":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var UICorePlugin = function UICorePlugin(core) { $traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]); this.core = core; this.enabled = true; this.bindEvents(); this.render(); }; var $UICorePlugin = UICorePlugin; ($traceurRuntime.createClass)(UICorePlugin, { bindEvents: function() {}, getExternalInterface: function() { return {}; }, enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, destroy: function() { this.remove(); }, render: function() { this.$el.html(this.template()); this.$el.append(this.styler.getStyleFor(this.name)); this.core.$el.append(this.el); return this; } }, {}, UIObject); module.exports = UICorePlugin; },{"ui_object":"ui_object"}],"ui_object":[function(require,module,exports){ "use strict"; var $ = require('zepto'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var UIObject = function UIObject(options) { $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.cid = _.uniqueId('c'); this._ensureElement(); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./utils":9,"base_object":"base_object","underscore":"underscore","zepto":"zepto"}],"underscore":[function(require,module,exports){ // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); },{}],"zepto":[function(require,module,exports){ /* Zepto v1.1.4-76-g2bd5d7a - zepto event ajax callbacks deferred touch selector - zeptojs.com/license */ var Zepto=function(){function D(t){return null==t?String(t):j[S.call(t)]||"object"}function L(t){return"function"==D(t)}function k(t){return null!=t&&t==t.window}function Z(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function $(t){return"object"==D(t)}function F(t){return $(t)&&!k(t)&&Object.getPrototypeOf(t)==Object.prototype}function R(t){return"number"==typeof t.length}function q(t){return s.call(t,function(t){return null!=t})}function W(t){return t.length>0?n.fn.concat.apply([],t):t}function z(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function H(t){return t in c?c[t]:c[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function _(t,e){return"number"!=typeof e||l[z(t)]?e:e+"px"}function I(t){var e,n;return f[t]||(e=u.createElement(t),u.body.appendChild(e),n=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==n&&(n="block"),f[t]=n),f[t]}function U(t){return"children"in t?a.call(t.children):n.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function X(t,e){var n,i=t?t.length:0;for(n=0;i>n;n++)this[n]=t[n];this.length=i,this.selector=e||""}function B(n,i,r){for(e in i)r&&(F(i[e])||A(i[e]))?(F(i[e])&&!F(n[e])&&(n[e]={}),A(i[e])&&!A(n[e])&&(n[e]=[]),B(n[e],i[e],r)):i[e]!==t&&(n[e]=i[e])}function V(t,e){return null==e?n(t):n(t).filter(e)}function Y(t,e,n,i){return L(e)?e.call(t,n,i):e}function J(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function G(e,n){var i=e.className||"",r=i&&i.baseVal!==t;return n===t?r?i.baseVal:i:void(r?i.baseVal=n:e.className=n)}function K(t){try{return t?"true"==t||("false"==t?!1:"null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?n.parseJSON(t):t):t}catch(e){return t}}function Q(t,e){e(t);for(var n=0,i=t.childNodes.length;i>n;n++)Q(t.childNodes[n],e)}var t,e,n,i,N,P,r=[],o=r.concat,s=r.filter,a=r.slice,u=window.document,f={},c={},l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},h=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,d=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,m=/^(?:body|html)$/i,g=/([A-Z])/g,v=["val","css","html","text","data","width","height","offset"],y=["after","prepend","before","append"],w=u.createElement("table"),x=u.createElement("tr"),b={tr:u.createElement("tbody"),tbody:w,thead:w,tfoot:w,td:x,th:x,"*":u.createElement("div")},E=/complete|loaded|interactive/,T=/^[\w-]*$/,j={},S=j.toString,C={},O=u.createElement("div"),M={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},A=Array.isArray||function(t){return t instanceof Array};return C.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var i,r=t.parentNode,o=!r;return o&&(r=O).appendChild(t),i=~C.qsa(r,e).indexOf(t),o&&O.removeChild(t),i},N=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},P=function(t){return s.call(t,function(e,n){return t.indexOf(e)==n})},C.fragment=function(e,i,r){var o,s,f;return p.test(e)&&(o=n(u.createElement(RegExp.$1))),o||(e.replace&&(e=e.replace(d,"<$1></$2>")),i===t&&(i=h.test(e)&&RegExp.$1),i in b||(i="*"),f=b[i],f.innerHTML=""+e,o=n.each(a.call(f.childNodes),function(){f.removeChild(this)})),F(r)&&(s=n(o),n.each(r,function(t,e){v.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},C.Z=function(t,e){return new X(t,e)},C.isZ=function(t){return t instanceof C.Z},C.init=function(e,i){var r;if(!e)return C.Z();if("string"==typeof e)if(e=e.trim(),"<"==e[0]&&h.test(e))r=C.fragment(e,RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}else{if(L(e))return n(u).ready(e);if(C.isZ(e))return e;if(A(e))r=q(e);else if($(e))r=[e],e=null;else if(h.test(e))r=C.fragment(e.trim(),RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}}return C.Z(r,e)},n=function(t,e){return C.init(t,e)},n.extend=function(t){var e,n=a.call(arguments,1);return"boolean"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){B(t,n,e)}),t},C.qsa=function(t,e){var n,i="#"==e[0],r=!i&&"."==e[0],o=i||r?e.slice(1):e,s=T.test(o);return t.getElementById&&s&&i?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:a.call(s&&!i&&t.getElementsByClassName?r?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},n.contains=u.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},n.type=D,n.isFunction=L,n.isWindow=k,n.isArray=A,n.isPlainObject=F,n.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},n.inArray=function(t,e,n){return r.indexOf.call(e,t,n)},n.camelCase=N,n.trim=function(t){return null==t?"":String.prototype.trim.call(t)},n.uuid=0,n.support={},n.expr={},n.noop=function(){},n.map=function(t,e){var n,r,o,i=[];if(R(t))for(r=0;r<t.length;r++)n=e(t[r],r),null!=n&&i.push(n);else for(o in t)n=e(t[o],o),null!=n&&i.push(n);return W(i)},n.each=function(t,e){var n,i;if(R(t)){for(n=0;n<t.length;n++)if(e.call(t[n],n,t[n])===!1)return t}else for(i in t)if(e.call(t[i],i,t[i])===!1)return t;return t},n.grep=function(t,e){return s.call(t,e)},window.JSON&&(n.parseJSON=JSON.parse),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){j["[object "+e+"]"]=e.toLowerCase()}),n.fn={constructor:C.Z,length:0,forEach:r.forEach,reduce:r.reduce,push:r.push,sort:r.sort,splice:r.splice,indexOf:r.indexOf,concat:function(){var t,e,n=[];for(t=0;t<arguments.length;t++)e=arguments[t],n[t]=C.isZ(e)?e.toArray():e;return o.apply(C.isZ(this)?this.toArray():this,n)},map:function(t){return n(n.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return n(a.apply(this,arguments))},ready:function(t){return E.test(u.readyState)&&u.body?t(n):u.addEventListener("DOMContentLoaded",function(){t(n)},!1),this},get:function(e){return e===t?a.call(this):this[e>=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return r.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return L(t)?this.not(this.not(t)):n(s.call(this,function(e){return C.matches(e,t)}))},add:function(t,e){return n(P(this.concat(n(t,e))))},is:function(t){return this.length>0&&C.matches(this[0],t)},not:function(e){var i=[];if(L(e)&&e.call!==t)this.each(function(t){e.call(this,t)||i.push(this)});else{var r="string"==typeof e?this.filter(e):R(e)&&L(e.item)?a.call(e):n(e);this.forEach(function(t){r.indexOf(t)<0&&i.push(t)})}return n(i)},has:function(t){return this.filter(function(){return $(t)?n.contains(this,t):n(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!$(t)?t:n(t)},last:function(){var t=this[this.length-1];return t&&!$(t)?t:n(t)},find:function(t){var e,i=this;return e=t?"object"==typeof t?n(t).filter(function(){var t=this;return r.some.call(i,function(e){return n.contains(e,t)})}):1==this.length?n(C.qsa(this[0],t)):this.map(function(){return C.qsa(this,t)}):n()},closest:function(t,e){var i=this[0],r=!1;for("object"==typeof t&&(r=n(t));i&&!(r?r.indexOf(i)>=0:C.matches(i,t));)i=i!==e&&!Z(i)&&i.parentNode;return n(i)},parents:function(t){for(var e=[],i=this;i.length>0;)i=n.map(i,function(t){return(t=t.parentNode)&&!Z(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return V(e,t)},parent:function(t){return V(P(this.pluck("parentNode")),t)},children:function(t){return V(this.map(function(){return U(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||a.call(this.childNodes)})},siblings:function(t){return V(this.map(function(t,e){return s.call(U(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(t){return n.map(this,function(e){return e[t]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=I(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=L(t);if(this[0]&&!e)var i=n(t).get(0),r=i.parentNode||this.length>1;return this.each(function(o){n(this).wrapAll(e?t.call(this,o):r?i.cloneNode(!0):i)})},wrapAll:function(t){if(this[0]){n(this[0]).before(t=n(t));for(var e;(e=t.children()).length;)t=e.first();n(t).append(this)}return this},wrapInner:function(t){var e=L(t);return this.each(function(i){var r=n(this),o=r.contents(),s=e?t.call(this,i):t;o.length?o.wrapAll(s):r.append(s)})},unwrap:function(){return this.parent().each(function(){n(this).replaceWith(n(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(e){return this.each(function(){var i=n(this);(e===t?"none"==i.css("display"):e)?i.show():i.hide()})},prev:function(t){return n(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return n(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each(function(e){var i=this.innerHTML;n(this).empty().append(Y(this,t,e,i))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?"":""+n}):0 in this?this[0].textContent:null},attr:function(n,i){var r;return"string"!=typeof n||1 in arguments?this.each(function(t){if(1===this.nodeType)if($(n))for(e in n)J(this,e,n[e]);else J(this,n,Y(this,i,t,this.getAttribute(n)))}):this.length&&1===this[0].nodeType?!(r=this[0].getAttribute(n))&&n in this[0]?this[0][n]:r:t},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(" ").forEach(function(t){J(this,t)},this)})},prop:function(t,e){return t=M[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},data:function(e,n){var i="data-"+e.replace(g,"-$1").toLowerCase(),r=1 in arguments?this.attr(i,n):this.attr(i);return null!==r?K(r):t},val:function(t){return 0 in arguments?this.each(function(e){this.value=Y(this,t,e,this.value)}):this[0]&&(this[0].multiple?n(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(t){if(t)return this.each(function(e){var i=n(this),r=Y(this,t,e,i.offset()),o=i.offsetParent().offset(),s={top:r.top-o.top,left:r.left-o.left};"static"==i.css("position")&&(s.position="relative"),i.css(s)});if(!this.length)return null;var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,i){if(arguments.length<2){var r,o=this[0];if(!o)return;if(r=getComputedStyle(o,""),"string"==typeof t)return o.style[N(t)]||r.getPropertyValue(t);if(A(t)){var s={};return n.each(t,function(t,e){s[e]=o.style[N(e)]||r.getPropertyValue(e)}),s}}var a="";if("string"==D(t))i||0===i?a=z(t)+":"+_(t,i):this.each(function(){this.style.removeProperty(z(t))});else for(e in t)t[e]||0===t[e]?a+=z(e)+":"+_(e,t[e])+";":this.each(function(){this.style.removeProperty(z(e))});return this.each(function(){this.style.cssText+=";"+a})},index:function(t){return t?this.indexOf(n(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?r.some.call(this,function(t){return this.test(G(t))},H(t)):!1},addClass:function(t){return t?this.each(function(e){if("className"in this){i=[];var r=G(this),o=Y(this,t,e,r);o.split(/\s+/g).forEach(function(t){n(this).hasClass(t)||i.push(t)},this),i.length&&G(this,r+(r?" ":"")+i.join(" "))}}):this},removeClass:function(e){return this.each(function(n){if("className"in this){if(e===t)return G(this,"");i=G(this),Y(this,e,n,i).split(/\s+/g).forEach(function(t){i=i.replace(H(t)," ")}),G(this,i.trim())}})},toggleClass:function(e,i){return e?this.each(function(r){var o=n(this),s=Y(this,e,r,G(this));s.split(/\s+/g).forEach(function(e){(i===t?!o.hasClass(e):i)?o.addClass(e):o.removeClass(e)})}):this},scrollTop:function(e){if(this.length){var n="scrollTop"in this[0];return e===t?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var n="scrollLeft"in this[0];return e===t?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),i=this.offset(),r=m.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(n(t).css("margin-top"))||0,i.left-=parseFloat(n(t).css("margin-left"))||0,r.top+=parseFloat(n(e[0]).css("border-top-width"))||0,r.left+=parseFloat(n(e[0]).css("border-left-width"))||0,{top:i.top-r.top,left:i.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||u.body;t&&!m.test(t.nodeName)&&"static"==n(t).css("position");)t=t.offsetParent;return t})}},n.fn.detach=n.fn.remove,["width","height"].forEach(function(e){var i=e.replace(/./,function(t){return t[0].toUpperCase()});n.fn[e]=function(r){var o,s=this[0];return r===t?k(s)?s["inner"+i]:Z(s)?s.documentElement["scroll"+i]:(o=this.offset())&&o[e]:this.each(function(t){s=n(this),s.css(e,Y(this,r,t,s[e]()))})}}),y.forEach(function(t,e){var i=e%2;n.fn[t]=function(){var t,o,r=n.map(arguments,function(e){return t=D(e),"object"==t||"array"==t||null==e?e:C.fragment(e)}),s=this.length>1;return r.length<1?this:this.each(function(t,a){o=i?a:a.parentNode,a=0==e?a.nextSibling:1==e?a.firstChild:2==e?a:null;var f=n.contains(u.documentElement,o);r.forEach(function(t){if(s)t=t.cloneNode(!0);else if(!o)return n(t).remove();o.insertBefore(t,a),f&&Q(t,function(t){null==t.nodeName||"SCRIPT"!==t.nodeName.toUpperCase()||t.type&&"text/javascript"!==t.type||t.src||window.eval.call(window,t.innerHTML)})})})},n.fn[i?t+"To":"insert"+(e?"Before":"After")]=function(e){return n(e)[t](this),this}}),C.Z.prototype=X.prototype=n.fn,C.uniq=P,C.deserializeValue=K,n.zepto=C,n}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(t){function l(t){return t._zid||(t._zid=e++)}function h(t,e,n,i){if(e=p(e),e.ns)var r=d(e.ns);return(s[l(t)]||[]).filter(function(t){return!(!t||e.e&&t.e!=e.e||e.ns&&!r.test(t.ns)||n&&l(t.fn)!==l(n)||i&&t.sel!=i)})}function p(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function d(t){return new RegExp("(?:^| )"+t.replace(" "," .* ?")+"(?: |$)")}function m(t,e){return t.del&&!u&&t.e in f||!!e}function g(t){return c[t]||u&&f[t]||t}function v(e,i,r,o,a,u,f){var h=l(e),d=s[h]||(s[h]=[]);i.split(/\s/).forEach(function(i){if("ready"==i)return t(document).ready(r);var s=p(i);s.fn=r,s.sel=a,s.e in c&&(r=function(e){var n=e.relatedTarget;return!n||n!==this&&!t.contains(this,n)?s.fn.apply(this,arguments):void 0}),s.del=u;var l=u||r;s.proxy=function(t){if(t=T(t),!t.isImmediatePropagationStopped()){t.data=o;var i=l.apply(e,t._args==n?[t]:[t].concat(t._args));return i===!1&&(t.preventDefault(),t.stopPropagation()),i}},s.i=d.length,d.push(s),"addEventListener"in e&&e.addEventListener(g(s.e),s.proxy,m(s,f))})}function y(t,e,n,i,r){var o=l(t);(e||"").split(/\s/).forEach(function(e){h(t,e,n,i).forEach(function(e){delete s[o][e.i],"removeEventListener"in t&&t.removeEventListener(g(e.e),e.proxy,m(e,r))})})}function T(e,i){return(i||!e.isDefaultPrevented)&&(i||(i=e),t.each(E,function(t,n){var r=i[t];e[t]=function(){return this[n]=w,r&&r.apply(i,arguments)},e[n]=x}),(i.defaultPrevented!==n?i.defaultPrevented:"returnValue"in i?i.returnValue===!1:i.getPreventDefault&&i.getPreventDefault())&&(e.isDefaultPrevented=w)),e}function j(t){var e,i={originalEvent:t};for(e in t)b.test(e)||t[e]===n||(i[e]=t[e]);return T(i,t)}var n,e=1,i=Array.prototype.slice,r=t.isFunction,o=function(t){return"string"==typeof t},s={},a={},u="onfocusin"in window,f={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};a.click=a.mousedown=a.mouseup=a.mousemove="MouseEvents",t.event={add:v,remove:y},t.proxy=function(e,n){var s=2 in arguments&&i.call(arguments,2);if(r(e)){var a=function(){return e.apply(n,s?s.concat(i.call(arguments)):arguments)};return a._zid=l(e),a}if(o(n))return s?(s.unshift(e[n],e),t.proxy.apply(null,s)):t.proxy(e[n],e);throw new TypeError("expected function")},t.fn.bind=function(t,e,n){return this.on(t,e,n)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,n,i){return this.on(t,e,n,i,1)};var w=function(){return!0},x=function(){return!1},b=/^([A-Z]|returnValue$|layer[XY]$)/,E={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};t.fn.delegate=function(t,e,n){return this.on(e,t,n)},t.fn.undelegate=function(t,e,n){return this.off(e,t,n)},t.fn.live=function(e,n){return t(document.body).delegate(this.selector,e,n),this},t.fn.die=function(e,n){return t(document.body).undelegate(this.selector,e,n),this},t.fn.on=function(e,s,a,u,f){var c,l,h=this;return e&&!o(e)?(t.each(e,function(t,e){h.on(t,s,a,e,f)}),h):(o(s)||r(u)||u===!1||(u=a,a=s,s=n),(u===n||a===!1)&&(u=a,a=n),u===!1&&(u=x),h.each(function(n,r){f&&(c=function(t){return y(r,t.type,u),u.apply(this,arguments)}),s&&(l=function(e){var n,o=t(e.target).closest(s,r).get(0);return o&&o!==r?(n=t.extend(j(e),{currentTarget:o,liveFired:r}),(c||u).apply(o,[n].concat(i.call(arguments,1)))):void 0}),v(r,e,u,a,s,l||c)}))},t.fn.off=function(e,i,s){var a=this;return e&&!o(e)?(t.each(e,function(t,e){a.off(t,i,e)}),a):(o(i)||r(s)||s===!1||(s=i,i=n),s===!1&&(s=x),a.each(function(){y(this,e,s,i)}))},t.fn.trigger=function(e,n){return e=o(e)||t.isPlainObject(e)?t.Event(e):T(e),e._args=n,this.each(function(){e.type in f&&"function"==typeof this[e.type]?this[e.type]():"dispatchEvent"in this?this.dispatchEvent(e):t(this).triggerHandler(e,n)})},t.fn.triggerHandler=function(e,n){var i,r;return this.each(function(s,a){i=j(o(e)?t.Event(e):e),i._args=n,i.target=a,t.each(h(a,e.type||e),function(t,e){return r=e.proxy(i),i.isImmediatePropagationStopped()?!1:void 0})}),r},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}}),t.Event=function(t,e){o(t)||(e=t,t=e.type);var n=document.createEvent(a[t]||"Events"),i=!0;if(e)for(var r in e)"bubbles"==r?i=!!e[r]:n[r]=e[r];return n.initEvent(t,i,!0),T(n)}}(Zepto),function(t){function h(e,n,i){var r=t.Event(n);return t(e).trigger(r,i),!r.isDefaultPrevented()}function p(t,e,i,r){return t.global?h(e||n,i,r):void 0}function d(e){e.global&&0===t.active++&&p(e,null,"ajaxStart")}function m(e){e.global&&!--t.active&&p(e,null,"ajaxStop")}function g(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||p(e,n,"ajaxBeforeSend",[t,e])===!1?!1:void p(e,n,"ajaxSend",[t,e])}function v(t,e,n,i){var r=n.context,o="success";n.success.call(r,t,o,e),i&&i.resolveWith(r,[t,o,e]),p(n,r,"ajaxSuccess",[e,n,t]),w(o,e,n)}function y(t,e,n,i,r){var o=i.context;i.error.call(o,n,e,t),r&&r.rejectWith(o,[n,e,t]),p(i,o,"ajaxError",[n,i,t||e]),w(e,n,i)}function w(t,e,n){var i=n.context;n.complete.call(i,e,t),p(n,i,"ajaxComplete",[e,n]),m(n)}function x(){}function b(t){return t&&(t=t.split(";",2)[0]),t&&(t==f?"html":t==u?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}function E(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function T(e){e.processData&&e.data&&"string"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&"GET"!=e.type.toUpperCase()||(e.url=E(e.url,e.data),e.data=void 0)}function j(e,n,i,r){return t.isFunction(n)&&(r=i,i=n,n=void 0),t.isFunction(i)||(r=i,i=void 0),{url:e,data:n,success:i,dataType:r}}function C(e,n,i,r){var o,s=t.isArray(n),a=t.isPlainObject(n);t.each(n,function(n,u){o=t.type(u),r&&(n=i?r:r+"["+(a||"object"==o||"array"==o?n:"")+"]"),!r&&s?e.add(u.name,u.value):"array"==o||!i&&"object"==o?C(e,u,i,n):e.add(n,u)})}var i,r,e=0,n=window.document,o=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,u="application/json",f="text/html",c=/^\s*$/,l=n.createElement("a");l.href=window.location.href,t.active=0,t.ajaxJSONP=function(i,r){if(!("type"in i))return t.ajax(i);var f,h,o=i.jsonpCallback,s=(t.isFunction(o)?o():o)||"jsonp"+ ++e,a=n.createElement("script"),u=window[s],c=function(e){t(a).triggerHandler("error",e||"abort")},l={abort:c};return r&&r.promise(l),t(a).on("load error",function(e,n){clearTimeout(h),t(a).off().remove(),"error"!=e.type&&f?v(f[0],l,i,r):y(null,n||"error",l,i,r),window[s]=u,f&&t.isFunction(u)&&u(f[0]),u=f=void 0}),g(l,i)===!1?(c("abort"),l):(window[s]=function(){f=arguments},a.src=i.url.replace(/\?(.+)=\?/,"?$1="+s),n.head.appendChild(a),i.timeout>0&&(h=setTimeout(function(){c("timeout")},i.timeout)),l)},t.ajaxSettings={type:"GET",beforeSend:x,success:x,error:x,complete:x,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:u,xml:"application/xml, text/xml",html:f,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},t.ajax=function(e){var a,u,o=t.extend({},e||{}),s=t.Deferred&&t.Deferred();for(i in t.ajaxSettings)void 0===o[i]&&(o[i]=t.ajaxSettings[i]);d(o),o.crossDomain||(a=n.createElement("a"),a.href=o.url,a.href=a.href,o.crossDomain=l.protocol+"//"+l.host!=a.protocol+"//"+a.host),o.url||(o.url=window.location.toString()),(u=o.url.indexOf("#"))>-1&&(o.url=o.url.slice(0,u)),T(o);var f=o.dataType,h=/\?.+=\?/.test(o.url);if(h&&(f="jsonp"),o.cache!==!1&&(e&&e.cache===!0||"script"!=f&&"jsonp"!=f)||(o.url=E(o.url,"_="+Date.now())),"jsonp"==f)return h||(o.url=E(o.url,o.jsonp?o.jsonp+"=?":o.jsonp===!1?"":"callback=?")),t.ajaxJSONP(o,s);var N,p=o.accepts[f],m={},w=function(t,e){m[t.toLowerCase()]=[t,e]},j=/^([\w-]+:)\/\//.test(o.url)?RegExp.$1:window.location.protocol,S=o.xhr(),C=S.setRequestHeader;if(s&&s.promise(S),o.crossDomain||w("X-Requested-With","XMLHttpRequest"),w("Accept",p||"*/*"),(p=o.mimeType||p)&&(p.indexOf(",")>-1&&(p=p.split(",",2)[0]),S.overrideMimeType&&S.overrideMimeType(p)),(o.contentType||o.contentType!==!1&&o.data&&"GET"!=o.type.toUpperCase())&&w("Content-Type",o.contentType||"application/x-www-form-urlencoded"),o.headers)for(r in o.headers)w(r,o.headers[r]);if(S.setRequestHeader=w,S.onreadystatechange=function(){if(4==S.readyState){S.onreadystatechange=x,clearTimeout(N);var e,n=!1;if(S.status>=200&&S.status<300||304==S.status||0==S.status&&"file:"==j){f=f||b(o.mimeType||S.getResponseHeader("content-type")),e=S.responseText;try{"script"==f?(1,eval)(e):"xml"==f?e=S.responseXML:"json"==f&&(e=c.test(e)?null:t.parseJSON(e))}catch(i){n=i}n?y(n,"parsererror",S,o,s):v(e,S,o,s)}else y(S.statusText||null,S.status?"error":"abort",S,o,s)}},g(S,o)===!1)return S.abort(),y(null,"abort",S,o,s),S;if(o.xhrFields)for(r in o.xhrFields)S[r]=o.xhrFields[r];var P="async"in o?o.async:!0;S.open(o.type,o.url,P,o.username,o.password);for(r in m)C.apply(S,m[r]);return o.timeout>0&&(N=setTimeout(function(){S.onreadystatechange=x,S.abort(),y(null,"timeout",S,o,s)},o.timeout)),S.send(o.data?o.data:null),S},t.get=function(){return t.ajax(j.apply(null,arguments))},t.post=function(){var e=j.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=j.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,n,i){if(!this.length)return this;var a,r=this,s=e.split(/\s/),u=j(e,n,i),f=u.success;return s.length>1&&(u.url=s[0],a=s[1]),u.success=function(e){r.html(a?t("<div>").html(e.replace(o,"")).find(a):e),f&&f.apply(r,arguments)},t.ajax(u),this};var S=encodeURIComponent;t.param=function(e,n){var i=[];return i.add=function(e,n){t.isFunction(n)&&(n=n()),null==n&&(n=""),this.push(S(e)+"="+S(n))},C(i,e,n),i.join("&").replace(/%20/g,"+")}}(Zepto),function(t){t.Callbacks=function(e){e=t.extend({},e);var n,i,r,o,s,a,u=[],f=!e.once&&[],c=function(t){for(n=e.memory&&t,i=!0,a=o||0,o=0,s=u.length,r=!0;u&&s>a;++a)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}r=!1,u&&(f?f.length&&c(f.shift()):n?u.length=0:l.disable())},l={add:function(){if(u){var i=u.length,a=function(n){t.each(n,function(t,n){"function"==typeof n?e.unique&&l.has(n)||u.push(n):n&&n.length&&"string"!=typeof n&&a(n)})};a(arguments),r?s=u.length:n&&(o=i,c(n))}return this},remove:function(){return u&&t.each(arguments,function(e,n){for(var i;(i=t.inArray(n,u,i))>-1;)u.splice(i,1),r&&(s>=i&&--s,a>=i&&--a)}),this},has:function(e){return!(!u||!(e?t.inArray(e,u)>-1:u.length))},empty:function(){return s=u.length=0,this},disable:function(){return u=f=n=void 0,this},disabled:function(){return!u},lock:function(){return f=void 0,n||l.disable(),this},locked:function(){return!f},fireWith:function(t,e){return!u||i&&!f||(e=e||[],e=[t,e.slice?e.slice():e],r?f.push(e):c(e)),this},fire:function(){return l.fireWith(this,arguments)},fired:function(){return!!i}};return l}}(Zepto),function(t){function n(e){var i=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",o={state:function(){return r},always:function(){return s.done(arguments).fail(arguments),this},then:function(){var e=arguments;return n(function(n){t.each(i,function(i,r){var a=t.isFunction(e[i])&&e[i];s[r[1]](function(){var e=a&&a.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(n.resolve).fail(n.reject).progress(n.notify);else{var i=this===o?n.promise():this,s=a?[e]:arguments;n[r[0]+"With"](i,s)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,o):o}},s={};return t.each(i,function(t,e){var n=e[2],a=e[3];o[e[1]]=n.add,a&&n.add(function(){r=a},i[1^t][2].disable,i[2][2].lock),s[e[0]]=function(){return s[e[0]+"With"](this===s?o:this,arguments),this},s[e[0]+"With"]=n.fireWith}),o.promise(s),e&&e.call(s,s),s}var e=Array.prototype.slice;t.when=function(i){var f,c,l,r=e.call(arguments),o=r.length,s=0,a=1!==o||i&&t.isFunction(i.promise)?o:0,u=1===a?i:n(),h=function(t,n,i){return function(r){n[t]=this,i[t]=arguments.length>1?e.call(arguments):r,i===f?u.notifyWith(n,i):--a||u.resolveWith(n,i)}};if(o>1)for(f=new Array(o),c=new Array(o),l=new Array(o);o>s;++s)r[s]&&t.isFunction(r[s].promise)?r[s].promise().done(h(s,l,r)).fail(u.reject).progress(h(s,c,f)):--a;return a||u.resolveWith(l,r),u.promise()},t.Deferred=n}(Zepto),function(t){function u(t,e,n,i){return Math.abs(t-e)>=Math.abs(n-i)?t-e>0?"Left":"Right":n-i>0?"Up":"Down"}function f(){o=null,e.last&&(e.el.trigger("longTap"),e={})}function c(){o&&clearTimeout(o),o=null}function l(){n&&clearTimeout(n),i&&clearTimeout(i),r&&clearTimeout(r),o&&clearTimeout(o),n=i=r=o=null,e={}}function h(t){return("touch"==t.pointerType||t.pointerType==t.MSPOINTER_TYPE_TOUCH)&&t.isPrimary}function p(t,e){return t.type=="pointer"+e||t.type.toLowerCase()=="mspointer"+e}var n,i,r,o,a,e={},s=750;t(document).ready(function(){var d,m,y,w,g=0,v=0;"MSGesture"in window&&(a=new MSGesture,a.target=document.body),t(document).bind("MSGestureEnd",function(t){var n=t.velocityX>1?"Right":t.velocityX<-1?"Left":t.velocityY>1?"Down":t.velocityY<-1?"Up":null;n&&(e.el.trigger("swipe"),e.el.trigger("swipe"+n))}).on("touchstart MSPointerDown pointerdown",function(i){(!(w=p(i,"down"))||h(i))&&(y=w?i:i.touches[0],i.touches&&1===i.touches.length&&e.x2&&(e.x2=void 0,e.y2=void 0),d=Date.now(),m=d-(e.last||d),e.el=t("tagName"in y.target?y.target:y.target.parentNode),n&&clearTimeout(n),e.x1=y.pageX,e.y1=y.pageY,m>0&&250>=m&&(e.isDoubleTap=!0),e.last=d,o=setTimeout(f,s),a&&w&&a.addPointer(i.pointerId))}).on("touchmove MSPointerMove pointermove",function(t){(!(w=p(t,"move"))||h(t))&&(y=w?t:t.touches[0],c(),e.x2=y.pageX,e.y2=y.pageY,g+=Math.abs(e.x1-e.x2),v+=Math.abs(e.y1-e.y2))}).on("touchend MSPointerUp pointerup",function(o){(!(w=p(o,"up"))||h(o))&&(c(),e.x2&&Math.abs(e.x1-e.x2)>30||e.y2&&Math.abs(e.y1-e.y2)>30?r=setTimeout(function(){e.el.trigger("swipe"),e.el.trigger("swipe"+u(e.x1,e.x2,e.y1,e.y2)),e={}},0):"last"in e&&(30>g&&30>v?i=setTimeout(function(){var i=t.Event("tap");i.cancelTouch=l,e.el.trigger(i),e.isDoubleTap?(e.el&&e.el.trigger("doubleTap"),e={}):n=setTimeout(function(){n=null,e.el&&e.el.trigger("singleTap"),e={}},250)},0):e={}),g=v=0)}).on("touchcancel MSPointerCancel pointercancel",l),t(window).on("scroll",l)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(e){t.fn[e]=function(t){return this.on(e,t)}})}(Zepto),function(t){function r(e){return e=t(e),!(!e.width()&&!e.height())&&"none"!==e.css("display")}function f(t,e){t=t.replace(/=#\]/g,'="#"]');var n,i,r=s.exec(t);if(r&&r[2]in o&&(n=o[r[2]],i=r[3],t=r[1],i)){var a=Number(i);i=isNaN(a)?i.replace(/^["']|["']$/g,""):a}return e(t,n,i)}var e=t.zepto,n=e.qsa,i=e.matches,o=t.expr[":"]={visible:function(){return r(this)?this:void 0},hidden:function(){return r(this)?void 0:this},selected:function(){return this.selected?this:void 0},checked:function(){return this.checked?this:void 0},parent:function(){return this.parentNode},first:function(t){return 0===t?this:void 0},last:function(t,e){return t===e.length-1?this:void 0},eq:function(t,e,n){return t===n?this:void 0},contains:function(e,n,i){return t(this).text().indexOf(i)>-1?this:void 0},has:function(t,n,i){return e.qsa(this,i).length?this:void 0}},s=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),a=/^\s*>/,u="Zepto"+ +new Date;e.qsa=function(i,r){return f(r,function(o,s,f){try{var c;!o&&s?o="*":a.test(o)&&(c=t(i).addClass(u),o="."+u+" "+o);var l=n(i,o)}catch(h){throw console.error("error performing selector: %o",r),h}finally{c&&c.removeClass(u)}return s?e.uniq(t.map(l,function(t,e){return s.call(t,e,l,f)})):l})},e.matches=function(t,e){return f(e,function(e,n,r){return!(e&&!i(t,e)||n&&n.call(t,null,r)!==t)})}}(Zepto); module.exports = Zepto; },{}]},{},[3,1]) //# sourceMappingURL=clappr.map
ajax/libs/inferno/1.0.0-beta17/inferno-mobx.js
x112358/cdnjs
/*! * inferno-mobx v1.0.0-beta17 * (c) 2016 Ryan Megidov * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component'), require('./inferno'), require('./inferno-create-class'), require('./inferno-create-element')) : typeof define === 'function' && define.amd ? define(['inferno-component', 'inferno', 'inferno-create-class', 'inferno-create-element'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Mobx = factory(global.Inferno.Component,global.Inferno,global.Inferno.createClass,global.Inferno.createElement)); }(this, (function (Component,Inferno,createClass,createElement) { 'use strict'; Component = 'default' in Component ? Component['default'] : Component; Inferno = 'default' in Inferno ? Inferno['default'] : Inferno; createClass = 'default' in createClass ? createClass['default'] : createClass; createElement = 'default' in createElement ? createElement['default'] : createElement; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } function warning(condition, message) { if (!condition) { console.error(message); } } var specialKeys = { children: true, key: true, ref: true }; var Provider = (function (Component$$1) { function Provider(props, context) { Component$$1.call(this, props, context); this.contextTypes = { mobxStores: function mobxStores() { } }; this.childContextTypes = { mobxStores: function mobxStores$1() { } }; this.store = props.store; } if ( Component$$1 ) Provider.__proto__ = Component$$1; Provider.prototype = Object.create( Component$$1 && Component$$1.prototype ); Provider.prototype.constructor = Provider; Provider.prototype.render = function render () { return this.props.children; }; Provider.prototype.getChildContext = function getChildContext () { var this$1 = this; var stores = {}; // inherit stores var baseStores = this.context.mobxStores; if (baseStores) { for (var key in baseStores) { stores[key] = baseStores[key]; } } // add own stores for (var key$1 in this.props) { if (!specialKeys[key$1]) { stores[key$1] = this$1.props[key$1]; } } return { mobxStores: stores }; }; return Provider; }(Component)); if (process.env.NODE_ENV !== 'production') { Provider.prototype.componentWillReceiveProps = function (nextProps) { var this$1 = this; // Maybe this warning is to aggressive? warning(Object.keys(nextProps).length === Object.keys(this.props).length, 'MobX Provider: The set of provided stores has changed. ' + 'Please avoid changing stores as the change might not propagate to all children'); for (var key in nextProps) { warning(specialKeys[key] || this$1.props[key] === nextProps[key], "MobX Provider: Provided store '" + key + "' has changed. " + "Please avoid replacing stores as the change might not propagate to all children"); } }; } var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var mobx = createCommonjsModule(function (module, exports) { "use strict"; var __extends = (commonjsGlobal && commonjsGlobal.__extends) || function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; registerGlobals(); exports.extras = { allowStateChanges: allowStateChanges, getAtom: getAtom, getDebugName: getDebugName, getDependencyTree: getDependencyTree, getObserverTree: getObserverTree, isComputingDerivation: isComputingDerivation, isSpyEnabled: isSpyEnabled, resetGlobalState: resetGlobalState, spyReport: spyReport, spyReportEnd: spyReportEnd, spyReportStart: spyReportStart, trackTransitions: trackTransitions, setReactionScheduler: setReactionScheduler }; exports._ = { getAdministration: getAdministration, resetGlobalState: resetGlobalState }; if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === 'object') { __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(module.exports); } var actionFieldDecorator = createClassPropertyDecorator(function (target, key, value, args, originalDescriptor) { var actionName = (args && args.length === 1) ? args[0] : (value.name || key || "<unnamed action>"); var wrappedAction = action(actionName, value); addHiddenProp(target, key, wrappedAction); }, function (key) { return this[key]; }, function () { invariant(false, "It is not allowed to assign new values to @action fields"); }, false, true); function action(arg1, arg2, arg3, arg4) { if (arguments.length === 1 && typeof arg1 === "function") { return createAction(arg1.name || "<unnamed action>", arg1); } if (arguments.length === 2 && typeof arg2 === "function") { return createAction(arg1, arg2); } if (arguments.length === 1 && typeof arg1 === "string") { return namedActionDecorator(arg1); } return namedActionDecorator(arg2).apply(null, arguments); } exports.action = action; function namedActionDecorator(name) { return function (target, prop, descriptor) { if (descriptor && typeof descriptor.value === "function") { descriptor.value = createAction(name, descriptor.value); descriptor.enumerable = false; descriptor.configurable = true; return descriptor; } return actionFieldDecorator(name).apply(this, arguments); }; } function runInAction(arg1, arg2, arg3) { var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>"; var fn = typeof arg1 === "function" ? arg1 : arg2; var scope = typeof arg1 === "function" ? arg2 : arg3; invariant(typeof fn === "function", "`runInAction` expects a function"); invariant(fn.length === 0, "`runInAction` expects a function without arguments"); invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'"); return executeAction(actionName, fn, scope, undefined); } exports.runInAction = runInAction; function isAction(thing) { return typeof thing === "function" && thing.isMobxAction === true; } exports.isAction = isAction; function autorun(arg1, arg2, arg3) { var name, view, scope; if (typeof arg1 === "string") { name = arg1; view = arg2; scope = arg3; } else if (typeof arg1 === "function") { name = arg1.name || ("Autorun@" + getNextId()); view = arg1; scope = arg2; } assertUnwrapped(view, "autorun methods cannot have modifiers"); invariant(typeof view === "function", "autorun expects a function"); invariant(isAction(view) === false, "Warning: attempted to pass an action to autorun. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."); if (scope) { view = view.bind(scope); } var reaction = new Reaction(name, function () { this.track(reactionRunner); }); function reactionRunner() { view(reaction); } reaction.schedule(); return reaction.getDisposer(); } exports.autorun = autorun; function when(arg1, arg2, arg3, arg4) { var name, predicate, effect, scope; if (typeof arg1 === "string") { name = arg1; predicate = arg2; effect = arg3; scope = arg4; } else if (typeof arg1 === "function") { name = ("When@" + getNextId()); predicate = arg1; effect = arg2; scope = arg3; } var disposer = autorun(name, function (r) { if (predicate.call(scope)) { r.dispose(); var prevUntracked = untrackedStart(); effect.call(scope); untrackedEnd(prevUntracked); } }); return disposer; } exports.when = when; function autorunUntil(predicate, effect, scope) { deprecated("`autorunUntil` is deprecated, please use `when`."); return when.apply(null, arguments); } exports.autorunUntil = autorunUntil; function autorunAsync(arg1, arg2, arg3, arg4) { var name, func, delay, scope; if (typeof arg1 === "string") { name = arg1; func = arg2; delay = arg3; scope = arg4; } else if (typeof arg1 === "function") { name = arg1.name || ("AutorunAsync@" + getNextId()); func = arg1; delay = arg2; scope = arg3; } invariant(isAction(func) === false, "Warning: attempted to pass an action to autorunAsync. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."); if (delay === void 0) { delay = 1; } if (scope) { func = func.bind(scope); } var isScheduled = false; var r = new Reaction(name, function () { if (!isScheduled) { isScheduled = true; setTimeout(function () { isScheduled = false; if (!r.isDisposed) { r.track(reactionRunner); } }, delay); } }); function reactionRunner() { func(r); } r.schedule(); return r.getDisposer(); } exports.autorunAsync = autorunAsync; function reaction(arg1, arg2, arg3, arg4, arg5, arg6) { var name, expression, effect, fireImmediately, delay, scope; if (typeof arg1 === "string") { name = arg1; expression = arg2; effect = arg3; fireImmediately = arg4; delay = arg5; scope = arg6; } else { name = arg1.name || arg2.name || ("Reaction@" + getNextId()); expression = arg1; effect = arg2; fireImmediately = arg3; delay = arg4; scope = arg5; } if (fireImmediately === void 0) { fireImmediately = false; } if (delay === void 0) { delay = 0; } var _a = getValueModeFromValue(expression, ValueMode.Reference), valueMode = _a[0], unwrappedExpression = _a[1]; var compareStructural = valueMode === ValueMode.Structure; if (scope) { unwrappedExpression = unwrappedExpression.bind(scope); effect = action(name, effect.bind(scope)); } var firstTime = true; var isScheduled = false; var nextValue = undefined; var r = new Reaction(name, function () { if (delay < 1) { reactionRunner(); } else if (!isScheduled) { isScheduled = true; setTimeout(function () { isScheduled = false; reactionRunner(); }, delay); } }); function reactionRunner() { if (r.isDisposed) { return; } var changed = false; r.track(function () { var v = unwrappedExpression(r); changed = valueDidChange(compareStructural, nextValue, v); nextValue = v; }); if (firstTime && fireImmediately) { effect(nextValue, r); } if (!firstTime && changed === true) { effect(nextValue, r); } if (firstTime) { firstTime = false; } } r.schedule(); return r.getDisposer(); } exports.reaction = reaction; var computedDecorator = createClassPropertyDecorator(function (target, name, _, decoratorArgs, originalDescriptor) { invariant(typeof originalDescriptor !== "undefined", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property."); var baseValue = originalDescriptor.get; var setter = originalDescriptor.set; invariant(typeof baseValue === "function", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'"); var compareStructural = false; if (decoratorArgs && decoratorArgs.length === 1 && decoratorArgs[0].asStructure === true) { compareStructural = true; } var adm = asObservableObject(target, undefined, ValueMode.Recursive); defineObservableProperty(adm, name, compareStructural ? asStructure(baseValue) : baseValue, false, setter); }, function (name) { var observable = this.$mobx.values[name]; if (observable === undefined) { return undefined; } return observable.get(); }, function (name, value) { this.$mobx.values[name].set(value); }, false, true); function computed(targetOrExpr, keyOrScopeOrSetter, baseDescriptor, options) { if (typeof targetOrExpr === "function" && arguments.length < 3) { if (typeof keyOrScopeOrSetter === "function") { return computedExpr(targetOrExpr, keyOrScopeOrSetter, undefined); } else { return computedExpr(targetOrExpr, undefined, keyOrScopeOrSetter); } } return computedDecorator.apply(null, arguments); } exports.computed = computed; function computedExpr(expr, setter, scope) { var _a = getValueModeFromValue(expr, ValueMode.Recursive), mode = _a[0], value = _a[1]; return new ComputedValue(value, scope, mode === ValueMode.Structure, value.name, setter); } function createTransformer(transformer, onCleanup) { invariant(typeof transformer === "function" && transformer.length === 1, "createTransformer expects a function that accepts one argument"); var objectCache = {}; var resetId = globalState.resetId; var Transformer = (function (_super) { __extends(Transformer, _super); function Transformer(sourceIdentifier, sourceObject) { _super.call(this, function () { return transformer(sourceObject); }, null, false, "Transformer-" + transformer.name + "-" + sourceIdentifier, undefined); this.sourceIdentifier = sourceIdentifier; this.sourceObject = sourceObject; } Transformer.prototype.onBecomeUnobserved = function () { var lastValue = this.value; _super.prototype.onBecomeUnobserved.call(this); delete objectCache[this.sourceIdentifier]; if (onCleanup) { onCleanup(lastValue, this.sourceObject); } }; return Transformer; }(ComputedValue)); return function (object) { if (resetId !== globalState.resetId) { objectCache = {}; resetId = globalState.resetId; } var identifier = getMemoizationId(object); var reactiveTransformer = objectCache[identifier]; if (reactiveTransformer) { return reactiveTransformer.get(); } reactiveTransformer = objectCache[identifier] = new Transformer(identifier, object); return reactiveTransformer.get(); }; } exports.createTransformer = createTransformer; function getMemoizationId(object) { if (object === null || typeof object !== "object") { throw new Error("[mobx] transform expected some kind of object, got: " + object); } var tid = object.$transformId; if (tid === undefined) { tid = getNextId(); addHiddenProp(object, "$transformId", tid); } return tid; } function expr(expr, scope) { if (!isComputingDerivation()) { console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."); } return computed(expr, scope).get(); } exports.expr = expr; function extendObservable(target) { var arguments$1 = arguments; var properties = []; for (var _i = 1; _i < arguments.length; _i++) { properties[_i - 1] = arguments$1[_i]; } invariant(arguments.length >= 2, "extendObservable expected 2 or more arguments"); invariant(typeof target === "object", "extendObservable expects an object as first argument"); invariant(!(isObservableMap(target)), "extendObservable should not be used on maps, use map.merge instead"); properties.forEach(function (propSet) { invariant(typeof propSet === "object", "all arguments of extendObservable should be objects"); invariant(!isObservable(propSet), "extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540"); extendObservableHelper(target, propSet, ValueMode.Recursive, null); }); return target; } exports.extendObservable = extendObservable; function extendObservableHelper(target, properties, mode, name) { var adm = asObservableObject(target, name, mode); for (var key in properties) { if (hasOwnProperty(properties, key)) { if (target === properties && !isPropertyConfigurable(target, key)) { continue; } var descriptor = Object.getOwnPropertyDescriptor(properties, key); setObservableObjectInstanceProperty(adm, key, descriptor); } } return target; } function getDependencyTree(thing, property) { return nodeToDependencyTree(getAtom(thing, property)); } function nodeToDependencyTree(node) { var result = { name: node.name }; if (node.observing && node.observing.length > 0) { result.dependencies = unique(node.observing).map(nodeToDependencyTree); } return result; } function getObserverTree(thing, property) { return nodeToObserverTree(getAtom(thing, property)); } function nodeToObserverTree(node) { var result = { name: node.name }; if (hasObservers(node)) { result.observers = getObservers(node).map(nodeToObserverTree); } return result; } function intercept(thing, propOrHandler, handler) { if (typeof handler === "function") { return interceptProperty(thing, propOrHandler, handler); } else { return interceptInterceptable(thing, propOrHandler); } } exports.intercept = intercept; function interceptInterceptable(thing, handler) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); return getAdministration(observable(thing)).intercept(handler); } return getAdministration(thing).intercept(handler); } function interceptProperty(thing, property, handler) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); extendObservable(thing, { property: thing[property] }); return interceptProperty(thing, property, handler); } return getAdministration(thing, property).intercept(handler); } function isComputed(value, property) { if (value === null || value === undefined) { return false; } if (property !== undefined) { if (isObservableObject(value) === false) { return false; } var atom = getAtom(value, property); return isComputedValue(atom); } return isComputedValue(value); } exports.isComputed = isComputed; function isObservable(value, property) { if (value === null || value === undefined) { return false; } if (property !== undefined) { if (isObservableArray(value) || isObservableMap(value)) { throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."); } else if (isObservableObject(value)) { var o = value.$mobx; return o.values && !!o.values[property]; } return false; } return !!value.$mobx || isAtom(value) || isReaction(value) || isComputedValue(value); } exports.isObservable = isObservable; var decoratorImpl = createClassPropertyDecorator(function (target, name, baseValue) { var prevA = allowStateChangesStart(true); if (typeof baseValue === "function") { baseValue = asReference(baseValue); } var adm = asObservableObject(target, undefined, ValueMode.Recursive); defineObservableProperty(adm, name, baseValue, true, undefined); allowStateChangesEnd(prevA); }, function (name) { var observable = this.$mobx.values[name]; if (observable === undefined) { return undefined; } return observable.get(); }, function (name, value) { setPropertyValue(this, name, value); }, true, false); function observableDecorator(target, key, baseDescriptor) { invariant(arguments.length >= 2 && arguments.length <= 3, "Illegal decorator config", key); assertPropertyConfigurable(target, key); invariant(!baseDescriptor || !baseDescriptor.get, "@observable can not be used on getters, use @computed instead"); return decoratorImpl.apply(null, arguments); } function observable(v, keyOrScope) { if (v === void 0) { v = undefined; } if (typeof arguments[1] === "string") { return observableDecorator.apply(null, arguments); } invariant(arguments.length < 3, "observable expects zero, one or two arguments"); if (isObservable(v)) { return v; } var _a = getValueModeFromValue(v, ValueMode.Recursive), mode = _a[0], value = _a[1]; var sourceType = mode === ValueMode.Reference ? ValueType.Reference : getTypeOfValue(value); switch (sourceType) { case ValueType.Array: case ValueType.PlainObject: return makeChildObservable(value, mode); case ValueType.Reference: case ValueType.ComplexObject: return new ObservableValue(value, mode); case ValueType.ComplexFunction: throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`"); case ValueType.ViewFunction: deprecated("Use `computed(expr)` instead of `observable(expr)`"); return computed(v, keyOrScope); } invariant(false, "Illegal State"); } exports.observable = observable; var ValueType; (function (ValueType) { ValueType[ValueType["Reference"] = 0] = "Reference"; ValueType[ValueType["PlainObject"] = 1] = "PlainObject"; ValueType[ValueType["ComplexObject"] = 2] = "ComplexObject"; ValueType[ValueType["Array"] = 3] = "Array"; ValueType[ValueType["ViewFunction"] = 4] = "ViewFunction"; ValueType[ValueType["ComplexFunction"] = 5] = "ComplexFunction"; })(ValueType || (ValueType = {})); function getTypeOfValue(value) { if (value === null || value === undefined) { return ValueType.Reference; } if (typeof value === "function") { return value.length ? ValueType.ComplexFunction : ValueType.ViewFunction; } if (isArrayLike(value)) { return ValueType.Array; } if (typeof value === "object") { return isPlainObject(value) ? ValueType.PlainObject : ValueType.ComplexObject; } return ValueType.Reference; } function observe(thing, propOrCb, cbOrFire, fireImmediately) { if (typeof cbOrFire === "function") { return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately); } else { return observeObservable(thing, propOrCb, cbOrFire); } } exports.observe = observe; function observeObservable(thing, listener, fireImmediately) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); return getAdministration(observable(thing)).observe(listener, fireImmediately); } return getAdministration(thing).observe(listener, fireImmediately); } function observeObservableProperty(thing, property, listener, fireImmediately) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); extendObservable(thing, { property: thing[property] }); return observeObservableProperty(thing, property, listener, fireImmediately); } return getAdministration(thing, property).observe(listener, fireImmediately); } function toJS(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } function cache(value) { if (detectCycles) { __alreadySeen.push([source, value]); } return value; } if (isObservable(source)) { if (detectCycles && __alreadySeen === null) { __alreadySeen = []; } if (detectCycles && source !== null && typeof source === "object") { for (var i = 0, l = __alreadySeen.length; i < l; i++) { if (__alreadySeen[i][0] === source) { return __alreadySeen[i][1]; } } } if (isObservableArray(source)) { var res = cache([]); var toAdd = source.map(function (value) { return toJS(value, detectCycles, __alreadySeen); }); res.length = toAdd.length; for (var i = 0, l = toAdd.length; i < l; i++) { res[i] = toAdd[i]; } return res; } if (isObservableObject(source)) { var res = cache({}); for (var key in source) { res[key] = toJS(source[key], detectCycles, __alreadySeen); } return res; } if (isObservableMap(source)) { var res_1 = cache({}); source.forEach(function (value, key) { return res_1[key] = toJS(value, detectCycles, __alreadySeen); }); return res_1; } if (isObservableValue(source)) { return toJS(source.get(), detectCycles, __alreadySeen); } } return source; } exports.toJS = toJS; function toJSlegacy(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } deprecated("toJSlegacy is deprecated and will be removed in the next major. Use `toJS` instead. See #566"); function cache(value) { if (detectCycles) { __alreadySeen.push([source, value]); } return value; } if (source instanceof Date || source instanceof RegExp) { return source; } if (detectCycles && __alreadySeen === null) { __alreadySeen = []; } if (detectCycles && source !== null && typeof source === "object") { for (var i = 0, l = __alreadySeen.length; i < l; i++) { if (__alreadySeen[i][0] === source) { return __alreadySeen[i][1]; } } } if (!source) { return source; } if (isArrayLike(source)) { var res = cache([]); var toAdd = source.map(function (value) { return toJSlegacy(value, detectCycles, __alreadySeen); }); res.length = toAdd.length; for (var i = 0, l = toAdd.length; i < l; i++) { res[i] = toAdd[i]; } return res; } if (isObservableMap(source)) { var res_2 = cache({}); source.forEach(function (value, key) { return res_2[key] = toJSlegacy(value, detectCycles, __alreadySeen); }); return res_2; } if (isObservableValue(source)) { return toJSlegacy(source.get(), detectCycles, __alreadySeen); } if (typeof source === "object") { var res = cache({}); for (var key in source) { res[key] = toJSlegacy(source[key], detectCycles, __alreadySeen); } return res; } return source; } exports.toJSlegacy = toJSlegacy; function toJSON(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } deprecated("toJSON is deprecated. Use toJS instead"); return toJSlegacy.apply(null, arguments); } exports.toJSON = toJSON; function log(msg) { console.log(msg); return msg; } function whyRun(thing, prop) { switch (arguments.length) { case 0: thing = globalState.trackingDerivation; if (!thing) { return log("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value."); } break; case 2: thing = getAtom(thing, prop); break; } thing = getAtom(thing); if (isComputedValue(thing)) { return log(thing.whyRun()); } else if (isReaction(thing)) { return log(thing.whyRun()); } else { invariant(false, "whyRun can only be used on reactions and computed values"); } } exports.whyRun = whyRun; function createAction(actionName, fn) { invariant(typeof fn === "function", "`action` can only be invoked on functions"); invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'"); var res = function () { return executeAction(actionName, fn, this, arguments); }; res.isMobxAction = true; return res; } function executeAction(actionName, fn, scope, args) { invariant(!isComputedValue(globalState.trackingDerivation), "Computed values or transformers should not invoke actions or trigger other side effects"); var notifySpy = isSpyEnabled(); var startTime; if (notifySpy) { startTime = Date.now(); var l = (args && args.length) || 0; var flattendArgs = new Array(l); if (l > 0) { for (var i = 0; i < l; i++) { flattendArgs[i] = args[i]; } } spyReportStart({ type: "action", name: actionName, fn: fn, target: scope, arguments: flattendArgs }); } var prevUntracked = untrackedStart(); transactionStart(actionName, scope, false); var prevAllowStateChanges = allowStateChangesStart(true); try { return fn.apply(scope, args); } finally { allowStateChangesEnd(prevAllowStateChanges); transactionEnd(false); untrackedEnd(prevUntracked); if (notifySpy) { spyReportEnd({ time: Date.now() - startTime }); } } } function useStrict(strict) { if (arguments.length === 0) { deprecated("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead"); return globalState.strictMode; } else { invariant(globalState.trackingDerivation === null, "It is not allowed to set `useStrict` when a derivation is running"); globalState.strictMode = strict; globalState.allowStateChanges = !strict; } } exports.useStrict = useStrict; function isStrictModeEnabled() { return globalState.strictMode; } exports.isStrictModeEnabled = isStrictModeEnabled; function allowStateChanges(allowStateChanges, func) { var prev = allowStateChangesStart(allowStateChanges); var res = func(); allowStateChangesEnd(prev); return res; } function allowStateChangesStart(allowStateChanges) { var prev = globalState.allowStateChanges; globalState.allowStateChanges = allowStateChanges; return prev; } function allowStateChangesEnd(prev) { globalState.allowStateChanges = prev; } var BaseAtom = (function () { function BaseAtom(name) { if (name === void 0) { name = "Atom@" + getNextId(); } this.name = name; this.isPendingUnobservation = true; this.observers = []; this.observersIndexes = {}; this.diffValue = 0; this.lastAccessedBy = 0; this.lowestObserverState = IDerivationState.NOT_TRACKING; } BaseAtom.prototype.onBecomeUnobserved = function () { }; BaseAtom.prototype.reportObserved = function () { reportObserved(this); }; BaseAtom.prototype.reportChanged = function () { transactionStart("propagatingAtomChange", null, false); propagateChanged(this); transactionEnd(false); }; BaseAtom.prototype.toString = function () { return this.name; }; return BaseAtom; }()); exports.BaseAtom = BaseAtom; var Atom = (function (_super) { __extends(Atom, _super); function Atom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { if (name === void 0) { name = "Atom@" + getNextId(); } if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; } if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; } _super.call(this, name); this.name = name; this.onBecomeObservedHandler = onBecomeObservedHandler; this.onBecomeUnobservedHandler = onBecomeUnobservedHandler; this.isPendingUnobservation = false; this.isBeingTracked = false; } Atom.prototype.reportObserved = function () { startBatch(); _super.prototype.reportObserved.call(this); if (!this.isBeingTracked) { this.isBeingTracked = true; this.onBecomeObservedHandler(); } endBatch(); return !!globalState.trackingDerivation; }; Atom.prototype.onBecomeUnobserved = function () { this.isBeingTracked = false; this.onBecomeUnobservedHandler(); }; return Atom; }(BaseAtom)); exports.Atom = Atom; var isAtom = createInstanceofPredicate("Atom", BaseAtom); var ComputedValue = (function () { function ComputedValue(derivation, scope, compareStructural, name, setter) { this.derivation = derivation; this.scope = scope; this.compareStructural = compareStructural; this.dependenciesState = IDerivationState.NOT_TRACKING; this.observing = []; this.newObserving = null; this.isPendingUnobservation = false; this.observers = []; this.observersIndexes = {}; this.diffValue = 0; this.runId = 0; this.lastAccessedBy = 0; this.lowestObserverState = IDerivationState.UP_TO_DATE; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.value = undefined; this.isComputing = false; this.isRunningSetter = false; this.name = name || "ComputedValue@" + getNextId(); if (setter) { this.setter = createAction(name + "-setter", setter); } } ComputedValue.prototype.peek = function () { this.isComputing = true; var prevAllowStateChanges = allowStateChangesStart(false); var res = this.derivation.call(this.scope); allowStateChangesEnd(prevAllowStateChanges); this.isComputing = false; return res; }; ComputedValue.prototype.peekUntracked = function () { var hasError = true; try { var res = this.peek(); hasError = false; return res; } finally { if (hasError) { handleExceptionInDerivation(this); } } }; ComputedValue.prototype.onBecomeStale = function () { propagateMaybeChanged(this); }; ComputedValue.prototype.onBecomeUnobserved = function () { invariant(this.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row"); clearObserving(this); this.value = undefined; }; ComputedValue.prototype.get = function () { invariant(!this.isComputing, "Cycle detected in computation " + this.name, this.derivation); startBatch(); if (globalState.inBatch === 1) { if (shouldCompute(this)) { this.value = this.peekUntracked(); } } else { reportObserved(this); if (shouldCompute(this)) { if (this.trackAndCompute()) { propagateChangeConfirmed(this); } } } var result = this.value; endBatch(); return result; }; ComputedValue.prototype.recoverFromError = function () { this.isComputing = false; }; ComputedValue.prototype.set = function (value) { if (this.setter) { invariant(!this.isRunningSetter, "The setter of computed value '" + this.name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"); this.isRunningSetter = true; try { this.setter.call(this.scope, value); } finally { this.isRunningSetter = false; } } else { invariant(false, "[ComputedValue '" + this.name + "'] It is not possible to assign a new value to a computed value."); } }; ComputedValue.prototype.trackAndCompute = function () { if (isSpyEnabled()) { spyReport({ object: this, type: "compute", fn: this.derivation, target: this.scope }); } var oldValue = this.value; var newValue = this.value = trackDerivedFunction(this, this.peek); return valueDidChange(this.compareStructural, newValue, oldValue); }; ComputedValue.prototype.observe = function (listener, fireImmediately) { var _this = this; var firstTime = true; var prevValue = undefined; return autorun(function () { var newValue = _this.get(); if (!firstTime || fireImmediately) { var prevU = untrackedStart(); listener(newValue, prevValue); untrackedEnd(prevU); } firstTime = false; prevValue = newValue; }); }; ComputedValue.prototype.toJSON = function () { return this.get(); }; ComputedValue.prototype.toString = function () { return this.name + "[" + this.derivation.toString() + "]"; }; ComputedValue.prototype.whyRun = function () { var isTracking = Boolean(globalState.trackingDerivation); var observing = unique(this.isComputing ? this.newObserving : this.observing).map(function (dep) { return dep.name; }); var observers = unique(getObservers(this).map(function (dep) { return dep.name; })); return (("\nWhyRun? computation '" + this.name + "':\n * Running because: " + (isTracking ? "[active] the value of this computation is needed by a reaction" : this.isComputing ? "[get] The value of this computed was requested outside a reaction" : "[idle] not running at the moment") + "\n") + (this.dependenciesState === IDerivationState.NOT_TRACKING ? " * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n" : " * This computation will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this.isComputing && isTracking) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n " + joinStrings(observers) + "\n")); }; return ComputedValue; }()); var isComputedValue = createInstanceofPredicate("ComputedValue", ComputedValue); var IDerivationState; (function (IDerivationState) { IDerivationState[IDerivationState["NOT_TRACKING"] = -1] = "NOT_TRACKING"; IDerivationState[IDerivationState["UP_TO_DATE"] = 0] = "UP_TO_DATE"; IDerivationState[IDerivationState["POSSIBLY_STALE"] = 1] = "POSSIBLY_STALE"; IDerivationState[IDerivationState["STALE"] = 2] = "STALE"; })(IDerivationState || (IDerivationState = {})); exports.IDerivationState = IDerivationState; function shouldCompute(derivation) { switch (derivation.dependenciesState) { case IDerivationState.UP_TO_DATE: return false; case IDerivationState.NOT_TRACKING: case IDerivationState.STALE: return true; case IDerivationState.POSSIBLY_STALE: { var hasError = true; var prevUntracked = untrackedStart(); try { var obs = derivation.observing, l = obs.length; for (var i = 0; i < l; i++) { var obj = obs[i]; if (isComputedValue(obj)) { obj.get(); if (derivation.dependenciesState === IDerivationState.STALE) { hasError = false; untrackedEnd(prevUntracked); return true; } } } hasError = false; changeDependenciesStateTo0(derivation); untrackedEnd(prevUntracked); return false; } finally { if (hasError) { changeDependenciesStateTo0(derivation); } } } } } function isComputingDerivation() { return globalState.trackingDerivation !== null; } function checkIfStateModificationsAreAllowed() { if (!globalState.allowStateChanges) { invariant(false, globalState.strictMode ? "It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended" : "It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects."); } } function trackDerivedFunction(derivation, f) { changeDependenciesStateTo0(derivation); derivation.newObserving = new Array(derivation.observing.length + 100); derivation.unboundDepsCount = 0; derivation.runId = ++globalState.runId; var prevTracking = globalState.trackingDerivation; globalState.trackingDerivation = derivation; var hasException = true; var result; try { result = f.call(derivation); hasException = false; } finally { if (hasException) { handleExceptionInDerivation(derivation); } else { globalState.trackingDerivation = prevTracking; bindDependencies(derivation); } } return result; } function handleExceptionInDerivation(derivation) { var message = ("[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. " + "These functions should never throw exceptions as MobX will not always be able to recover from them. " + ("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '" + derivation.name + "'. ") + "For more details see https://github.com/mobxjs/mobx/issues/462"); if (isSpyEnabled()) { spyReport({ type: "error", message: message }); } console.warn(message); changeDependenciesStateTo0(derivation); derivation.newObserving = null; derivation.unboundDepsCount = 0; derivation.recoverFromError(); endBatch(); resetGlobalState(); } function bindDependencies(derivation) { var prevObserving = derivation.observing; var observing = derivation.observing = derivation.newObserving; derivation.newObserving = null; var i0 = 0, l = derivation.unboundDepsCount; for (var i = 0; i < l; i++) { var dep = observing[i]; if (dep.diffValue === 0) { dep.diffValue = 1; if (i0 !== i) { observing[i0] = dep; } i0++; } } observing.length = i0; l = prevObserving.length; while (l--) { var dep = prevObserving[l]; if (dep.diffValue === 0) { removeObserver(dep, derivation); } dep.diffValue = 0; } while (i0--) { var dep = observing[i0]; if (dep.diffValue === 1) { dep.diffValue = 0; addObserver(dep, derivation); } } } function clearObserving(derivation) { var obs = derivation.observing; var i = obs.length; while (i--) { removeObserver(obs[i], derivation); } derivation.dependenciesState = IDerivationState.NOT_TRACKING; obs.length = 0; } function untracked(action) { var prev = untrackedStart(); var res = action(); untrackedEnd(prev); return res; } exports.untracked = untracked; function untrackedStart() { var prev = globalState.trackingDerivation; globalState.trackingDerivation = null; return prev; } function untrackedEnd(prev) { globalState.trackingDerivation = prev; } function changeDependenciesStateTo0(derivation) { if (derivation.dependenciesState === IDerivationState.UP_TO_DATE) { return; } derivation.dependenciesState = IDerivationState.UP_TO_DATE; var obs = derivation.observing; var i = obs.length; while (i--) { obs[i].lowestObserverState = IDerivationState.UP_TO_DATE; } } var persistentKeys = ["mobxGuid", "resetId", "spyListeners", "strictMode", "runId"]; var MobXGlobals = (function () { function MobXGlobals() { this.version = 4; this.trackingDerivation = null; this.runId = 0; this.mobxGuid = 0; this.inTransaction = 0; this.isRunningReactions = false; this.inBatch = 0; this.pendingUnobservations = []; this.pendingReactions = []; this.allowStateChanges = true; this.strictMode = false; this.resetId = 0; this.spyListeners = []; } return MobXGlobals; }()); var globalState = (function () { var res = new MobXGlobals(); if (commonjsGlobal.__mobservableTrackingStack || commonjsGlobal.__mobservableViewStack) { throw new Error("[mobx] An incompatible version of mobservable is already loaded."); } if (commonjsGlobal.__mobxGlobal && commonjsGlobal.__mobxGlobal.version !== res.version) { throw new Error("[mobx] An incompatible version of mobx is already loaded."); } if (commonjsGlobal.__mobxGlobal) { return commonjsGlobal.__mobxGlobal; } return commonjsGlobal.__mobxGlobal = res; })(); function registerGlobals() { } function resetGlobalState() { globalState.resetId++; var defaultGlobals = new MobXGlobals(); for (var key in defaultGlobals) { if (persistentKeys.indexOf(key) === -1) { globalState[key] = defaultGlobals[key]; } } globalState.allowStateChanges = !globalState.strictMode; } function hasObservers(observable) { return observable.observers && observable.observers.length > 0; } function getObservers(observable) { return observable.observers; } function invariantObservers(observable) { var list = observable.observers; var map = observable.observersIndexes; var l = list.length; for (var i = 0; i < l; i++) { var id = list[i].__mapid; if (i) { invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list"); } else { invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldnt be held in map."); } } invariant(list.length === 0 || Object.keys(map).length === list.length - 1, "INTERNAL ERROR there is no junk in map"); } function addObserver(observable, node) { var l = observable.observers.length; if (l) { observable.observersIndexes[node.__mapid] = l; } observable.observers[l] = node; if (observable.lowestObserverState > node.dependenciesState) { observable.lowestObserverState = node.dependenciesState; } } function removeObserver(observable, node) { if (observable.observers.length === 1) { observable.observers.length = 0; queueForUnobservation(observable); } else { var list = observable.observers; var map_1 = observable.observersIndexes; var filler = list.pop(); if (filler !== node) { var index = map_1[node.__mapid] || 0; if (index) { map_1[filler.__mapid] = index; } else { delete map_1[filler.__mapid]; } list[index] = filler; } delete map_1[node.__mapid]; } } function queueForUnobservation(observable) { if (!observable.isPendingUnobservation) { observable.isPendingUnobservation = true; globalState.pendingUnobservations.push(observable); } } function startBatch() { globalState.inBatch++; } function endBatch() { if (globalState.inBatch === 1) { var list = globalState.pendingUnobservations; for (var i = 0; i < list.length; i++) { var observable_1 = list[i]; observable_1.isPendingUnobservation = false; if (observable_1.observers.length === 0) { observable_1.onBecomeUnobserved(); } } globalState.pendingUnobservations = []; } globalState.inBatch--; } function reportObserved(observable) { var derivation = globalState.trackingDerivation; if (derivation !== null) { if (derivation.runId !== observable.lastAccessedBy) { observable.lastAccessedBy = derivation.runId; derivation.newObserving[derivation.unboundDepsCount++] = observable; } } else if (observable.observers.length === 0) { queueForUnobservation(observable); } } function invariantLOS(observable, msg) { var min = getObservers(observable).reduce(function (a, b) { return Math.min(a, b.dependenciesState); }, 2); if (min >= observable.lowestObserverState) { return; } throw new Error("lowestObserverState is wrong for " + msg + " because " + min + " < " + observable.lowestObserverState); } function propagateChanged(observable) { if (observable.lowestObserverState === IDerivationState.STALE) { return; } observable.lowestObserverState = IDerivationState.STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.UP_TO_DATE) { d.onBecomeStale(); } d.dependenciesState = IDerivationState.STALE; } } function propagateChangeConfirmed(observable) { if (observable.lowestObserverState === IDerivationState.STALE) { return; } observable.lowestObserverState = IDerivationState.STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.POSSIBLY_STALE) { d.dependenciesState = IDerivationState.STALE; } else if (d.dependenciesState === IDerivationState.UP_TO_DATE) { observable.lowestObserverState = IDerivationState.UP_TO_DATE; } } } function propagateMaybeChanged(observable) { if (observable.lowestObserverState !== IDerivationState.UP_TO_DATE) { return; } observable.lowestObserverState = IDerivationState.POSSIBLY_STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.UP_TO_DATE) { d.dependenciesState = IDerivationState.POSSIBLY_STALE; d.onBecomeStale(); } } } var Reaction = (function () { function Reaction(name, onInvalidate) { if (name === void 0) { name = "Reaction@" + getNextId(); } this.name = name; this.onInvalidate = onInvalidate; this.observing = []; this.newObserving = []; this.dependenciesState = IDerivationState.NOT_TRACKING; this.diffValue = 0; this.runId = 0; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.isDisposed = false; this._isScheduled = false; this._isTrackPending = false; this._isRunning = false; } Reaction.prototype.onBecomeStale = function () { this.schedule(); }; Reaction.prototype.schedule = function () { if (!this._isScheduled) { this._isScheduled = true; globalState.pendingReactions.push(this); startBatch(); runReactions(); endBatch(); } }; Reaction.prototype.isScheduled = function () { return this._isScheduled; }; Reaction.prototype.runReaction = function () { if (!this.isDisposed) { this._isScheduled = false; if (shouldCompute(this)) { this._isTrackPending = true; this.onInvalidate(); if (this._isTrackPending && isSpyEnabled()) { spyReport({ object: this, type: "scheduled-reaction" }); } } } }; Reaction.prototype.track = function (fn) { startBatch(); var notify = isSpyEnabled(); var startTime; if (notify) { startTime = Date.now(); spyReportStart({ object: this, type: "reaction", fn: fn }); } this._isRunning = true; trackDerivedFunction(this, fn); this._isRunning = false; this._isTrackPending = false; if (this.isDisposed) { clearObserving(this); } if (notify) { spyReportEnd({ time: Date.now() - startTime }); } endBatch(); }; Reaction.prototype.recoverFromError = function () { this._isRunning = false; this._isTrackPending = false; }; Reaction.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; if (!this._isRunning) { startBatch(); clearObserving(this); endBatch(); } } }; Reaction.prototype.getDisposer = function () { var r = this.dispose.bind(this); r.$mobx = this; return r; }; Reaction.prototype.toString = function () { return "Reaction[" + this.name + "]"; }; Reaction.prototype.whyRun = function () { var observing = unique(this._isRunning ? this.newObserving : this.observing).map(function (dep) { return dep.name; }); return ("\nWhyRun? reaction '" + this.name + "':\n * Status: [" + (this.isDisposed ? "stopped" : this._isRunning ? "running" : this.isScheduled() ? "scheduled" : "idle") + "]\n * This reaction will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this._isRunning) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"); }; return Reaction; }()); exports.Reaction = Reaction; var MAX_REACTION_ITERATIONS = 100; var reactionScheduler = function (f) { return f(); }; function runReactions() { if (globalState.isRunningReactions === true || globalState.inTransaction > 0) { return; } reactionScheduler(runReactionsHelper); } function runReactionsHelper() { globalState.isRunningReactions = true; var allReactions = globalState.pendingReactions; var iterations = 0; while (allReactions.length > 0) { if (++iterations === MAX_REACTION_ITERATIONS) { resetGlobalState(); throw new Error(("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations.") + (" Probably there is a cycle in the reactive function: " + allReactions[0])); } var remainingReactions = allReactions.splice(0); for (var i = 0, l = remainingReactions.length; i < l; i++) { remainingReactions[i].runReaction(); } } globalState.isRunningReactions = false; } var isReaction = createInstanceofPredicate("Reaction", Reaction); function setReactionScheduler(fn) { var baseScheduler = reactionScheduler; reactionScheduler = function (f) { return fn(function () { return baseScheduler(f); }); }; } function isSpyEnabled() { return !!globalState.spyListeners.length; } function spyReport(event) { if (!globalState.spyListeners.length) { return false; } var listeners = globalState.spyListeners; for (var i = 0, l = listeners.length; i < l; i++) { listeners[i](event); } } function spyReportStart(event) { var change = objectAssign({}, event, { spyReportStart: true }); spyReport(change); } var END_EVENT = { spyReportEnd: true }; function spyReportEnd(change) { if (change) { spyReport(objectAssign({}, change, END_EVENT)); } else { spyReport(END_EVENT); } } function spy(listener) { globalState.spyListeners.push(listener); return once(function () { var idx = globalState.spyListeners.indexOf(listener); if (idx !== -1) { globalState.spyListeners.splice(idx, 1); } }); } exports.spy = spy; function trackTransitions(onReport) { deprecated("trackTransitions is deprecated. Use mobx.spy instead"); if (typeof onReport === "boolean") { deprecated("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"); onReport = arguments[1]; } if (!onReport) { deprecated("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"); return function () { }; } return spy(onReport); } function transaction(action, thisArg, report) { if (thisArg === void 0) { thisArg = undefined; } if (report === void 0) { report = true; } transactionStart((action.name) || "anonymous transaction", thisArg, report); try { return action.call(thisArg); } finally { transactionEnd(report); } } exports.transaction = transaction; function transactionStart(name, thisArg, report) { if (thisArg === void 0) { thisArg = undefined; } if (report === void 0) { report = true; } startBatch(); globalState.inTransaction += 1; if (report && isSpyEnabled()) { spyReportStart({ type: "transaction", target: thisArg, name: name }); } } function transactionEnd(report) { if (report === void 0) { report = true; } if (--globalState.inTransaction === 0) { runReactions(); } if (report && isSpyEnabled()) { spyReportEnd(); } endBatch(); } function hasInterceptors(interceptable) { return (interceptable.interceptors && interceptable.interceptors.length > 0); } function registerInterceptor(interceptable, handler) { var interceptors = interceptable.interceptors || (interceptable.interceptors = []); interceptors.push(handler); return once(function () { var idx = interceptors.indexOf(handler); if (idx !== -1) { interceptors.splice(idx, 1); } }); } function interceptChange(interceptable, change) { var prevU = untrackedStart(); var interceptors = interceptable.interceptors; for (var i = 0, l = interceptors.length; i < l; i++) { change = interceptors[i](change); invariant(!change || change.type, "Intercept handlers should return nothing or a change object"); if (!change) { return null; } } untrackedEnd(prevU); return change; } function hasListeners(listenable) { return listenable.changeListeners && listenable.changeListeners.length > 0; } function registerListener(listenable, handler) { var listeners = listenable.changeListeners || (listenable.changeListeners = []); listeners.push(handler); return once(function () { var idx = listeners.indexOf(handler); if (idx !== -1) { listeners.splice(idx, 1); } }); } function notifyListeners(listenable, change) { var prevU = untrackedStart(); var listeners = listenable.changeListeners; if (!listeners) { return; } listeners = listeners.slice(); for (var i = 0, l = listeners.length; i < l; i++) { if (Array.isArray(change)) { listeners[i].apply(null, change); } else { listeners[i](change); } } untrackedEnd(prevU); } var ValueMode; (function (ValueMode) { ValueMode[ValueMode["Recursive"] = 0] = "Recursive"; ValueMode[ValueMode["Reference"] = 1] = "Reference"; ValueMode[ValueMode["Structure"] = 2] = "Structure"; ValueMode[ValueMode["Flat"] = 3] = "Flat"; })(ValueMode || (ValueMode = {})); function withModifier(modifier, value) { assertUnwrapped(value, "Modifiers are not allowed to be nested"); return { mobxModifier: modifier, value: value }; } function getModifier(value) { if (value) { return value.mobxModifier || null; } return null; } function asReference(value) { return withModifier(ValueMode.Reference, value); } exports.asReference = asReference; asReference.mobxModifier = ValueMode.Reference; function asStructure(value) { return withModifier(ValueMode.Structure, value); } exports.asStructure = asStructure; asStructure.mobxModifier = ValueMode.Structure; function asFlat(value) { return withModifier(ValueMode.Flat, value); } exports.asFlat = asFlat; asFlat.mobxModifier = ValueMode.Flat; function asMap(data, modifierFunc) { return map(data, modifierFunc); } exports.asMap = asMap; function getValueModeFromValue(value, defaultMode) { var mode = getModifier(value); if (mode) { return [mode, value.value]; } return [defaultMode, value]; } function getValueModeFromModifierFunc(func) { if (func === undefined) { return ValueMode.Recursive; } var mod = getModifier(func); invariant(mod !== null, "Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: " + func); return mod; } function makeChildObservable(value, parentMode, name) { var childMode; if (isObservable(value)) { return value; } switch (parentMode) { case ValueMode.Reference: return value; case ValueMode.Flat: assertUnwrapped(value, "Items inside 'asFlat' cannot have modifiers"); childMode = ValueMode.Reference; break; case ValueMode.Structure: assertUnwrapped(value, "Items inside 'asStructure' cannot have modifiers"); childMode = ValueMode.Structure; break; case ValueMode.Recursive: _a = getValueModeFromValue(value, ValueMode.Recursive), childMode = _a[0], value = _a[1]; break; default: invariant(false, "Illegal State"); } if (Array.isArray(value)) { return createObservableArray(value, childMode, name); } if (isPlainObject(value) && Object.isExtensible(value)) { return extendObservableHelper(value, value, childMode, name); } return value; var _a; } function assertUnwrapped(value, message) { if (getModifier(value) !== null) { throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. " + message); } } var safariPrototypeSetterInheritanceBug = (function () { var v = false; var p = {}; Object.defineProperty(p, "0", { set: function () { v = true; } }); Object.create(p)["0"] = 1; return v === false; })(); var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; var StubArray = (function () { function StubArray() { } return StubArray; }()); StubArray.prototype = []; var ObservableArrayAdministration = (function () { function ObservableArrayAdministration(name, mode, array, owned) { this.mode = mode; this.array = array; this.owned = owned; this.lastKnownLength = 0; this.interceptors = null; this.changeListeners = null; this.atom = new BaseAtom(name || ("ObservableArray@" + getNextId())); } ObservableArrayAdministration.prototype.makeReactiveArrayItem = function (value) { assertUnwrapped(value, "Array values cannot have modifiers"); if (this.mode === ValueMode.Flat || this.mode === ValueMode.Reference) { return value; } return makeChildObservable(value, this.mode, this.atom.name + "[..]"); }; ObservableArrayAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } if (fireImmediately) { listener({ object: this.array, type: "splice", index: 0, added: this.values.slice(), addedCount: this.values.length, removed: [], removedCount: 0 }); } return registerListener(this, listener); }; ObservableArrayAdministration.prototype.getArrayLength = function () { this.atom.reportObserved(); return this.values.length; }; ObservableArrayAdministration.prototype.setArrayLength = function (newLength) { if (typeof newLength !== "number" || newLength < 0) { throw new Error("[mobx.array] Out of range: " + newLength); } var currentLength = this.values.length; if (newLength === currentLength) { return; } else if (newLength > currentLength) { this.spliceWithArray(currentLength, 0, new Array(newLength - currentLength)); } else { this.spliceWithArray(newLength, currentLength - newLength); } }; ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) { if (oldLength !== this.lastKnownLength) { throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?"); } this.lastKnownLength += delta; if (delta > 0 && oldLength + delta + 1 > OBSERVABLE_ARRAY_BUFFER_SIZE) { reserveArrayBuffer(oldLength + delta + 1); } }; ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) { checkIfStateModificationsAreAllowed(); var length = this.values.length; if (index === undefined) { index = 0; } else if (index > length) { index = length; } else if (index < 0) { index = Math.max(0, length + index); } if (arguments.length === 1) { deleteCount = length - index; } else if (deleteCount === undefined || deleteCount === null) { deleteCount = 0; } else { deleteCount = Math.max(0, Math.min(deleteCount, length - index)); } if (newItems === undefined) { newItems = []; } if (hasInterceptors(this)) { var change = interceptChange(this, { object: this.array, type: "splice", index: index, removedCount: deleteCount, added: newItems }); if (!change) { return EMPTY_ARRAY; } deleteCount = change.removedCount; newItems = change.added; } newItems = newItems.map(this.makeReactiveArrayItem, this); var lengthDelta = newItems.length - deleteCount; this.updateArrayLength(length, lengthDelta); var res = (_a = this.values).splice.apply(_a, [index, deleteCount].concat(newItems)); if (deleteCount !== 0 || newItems.length !== 0) { this.notifyArraySplice(index, newItems, res); } return res; var _a; }; ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.array, type: "update", index: index, newValue: newValue, oldValue: oldValue } : null; if (notifySpy) { spyReportStart(change); } this.atom.reportChanged(); if (notify) { notifyListeners(this, change); } if (notifySpy) { spyReportEnd(); } }; ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.array, type: "splice", index: index, removed: removed, added: added, removedCount: removed.length, addedCount: added.length } : null; if (notifySpy) { spyReportStart(change); } this.atom.reportChanged(); if (notify) { notifyListeners(this, change); } if (notifySpy) { spyReportEnd(); } }; return ObservableArrayAdministration; }()); var ObservableArray = (function (_super) { __extends(ObservableArray, _super); function ObservableArray(initialValues, mode, name, owned) { if (owned === void 0) { owned = false; } _super.call(this); var adm = new ObservableArrayAdministration(name, mode, this, owned); addHiddenFinalProp(this, "$mobx", adm); if (initialValues && initialValues.length) { adm.updateArrayLength(0, initialValues.length); adm.values = initialValues.map(adm.makeReactiveArrayItem, adm); adm.notifyArraySplice(0, adm.values.slice(), EMPTY_ARRAY); } else { adm.values = []; } if (safariPrototypeSetterInheritanceBug) { Object.defineProperty(adm.array, "0", ENTRY_0); } } ObservableArray.prototype.intercept = function (handler) { return this.$mobx.intercept(handler); }; ObservableArray.prototype.observe = function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } return this.$mobx.observe(listener, fireImmediately); }; ObservableArray.prototype.clear = function () { return this.splice(0); }; ObservableArray.prototype.concat = function () { var arguments$1 = arguments; var arrays = []; for (var _i = 0; _i < arguments.length; _i++) { arrays[_i - 0] = arguments$1[_i]; } this.$mobx.atom.reportObserved(); return Array.prototype.concat.apply(this.slice(), arrays.map(function (a) { return isObservableArray(a) ? a.slice() : a; })); }; ObservableArray.prototype.replace = function (newItems) { return this.$mobx.spliceWithArray(0, this.$mobx.values.length, newItems); }; ObservableArray.prototype.toJS = function () { return this.slice(); }; ObservableArray.prototype.toJSON = function () { return this.toJS(); }; ObservableArray.prototype.peek = function () { return this.$mobx.values; }; ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) { var this$1 = this; if (fromIndex === void 0) { fromIndex = 0; } this.$mobx.atom.reportObserved(); var items = this.$mobx.values, l = items.length; for (var i = fromIndex; i < l; i++) { if (predicate.call(thisArg, items[i], i, this$1)) { return items[i]; } } return undefined; }; ObservableArray.prototype.splice = function (index, deleteCount) { var arguments$1 = arguments; var newItems = []; for (var _i = 2; _i < arguments.length; _i++) { newItems[_i - 2] = arguments$1[_i]; } switch (arguments.length) { case 0: return []; case 1: return this.$mobx.spliceWithArray(index); case 2: return this.$mobx.spliceWithArray(index, deleteCount); } return this.$mobx.spliceWithArray(index, deleteCount, newItems); }; ObservableArray.prototype.push = function () { var arguments$1 = arguments; var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments$1[_i]; } var adm = this.$mobx; adm.spliceWithArray(adm.values.length, 0, items); return adm.values.length; }; ObservableArray.prototype.pop = function () { return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0]; }; ObservableArray.prototype.shift = function () { return this.splice(0, 1)[0]; }; ObservableArray.prototype.unshift = function () { var arguments$1 = arguments; var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments$1[_i]; } var adm = this.$mobx; adm.spliceWithArray(0, 0, items); return adm.values.length; }; ObservableArray.prototype.reverse = function () { this.$mobx.atom.reportObserved(); var clone = this.slice(); return clone.reverse.apply(clone, arguments); }; ObservableArray.prototype.sort = function (compareFn) { this.$mobx.atom.reportObserved(); var clone = this.slice(); return clone.sort.apply(clone, arguments); }; ObservableArray.prototype.remove = function (value) { var idx = this.$mobx.values.indexOf(value); if (idx > -1) { this.splice(idx, 1); return true; } return false; }; ObservableArray.prototype.toString = function () { return "[mobx.array] " + Array.prototype.toString.apply(this.$mobx.values, arguments); }; ObservableArray.prototype.toLocaleString = function () { return "[mobx.array] " + Array.prototype.toLocaleString.apply(this.$mobx.values, arguments); }; return ObservableArray; }(StubArray)); declareIterator(ObservableArray.prototype, function () { return arrayAsIterator(this.slice()); }); makeNonEnumerable(ObservableArray.prototype, [ "constructor", "intercept", "observe", "clear", "concat", "replace", "toJS", "toJSON", "peek", "find", "splice", "push", "pop", "shift", "unshift", "reverse", "sort", "remove", "toString", "toLocaleString" ]); Object.defineProperty(ObservableArray.prototype, "length", { enumerable: false, configurable: true, get: function () { return this.$mobx.getArrayLength(); }, set: function (newLength) { this.$mobx.setArrayLength(newLength); } }); [ "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "reduce", "reduceRight", "slice", "some" ].forEach(function (funcName) { var baseFunc = Array.prototype[funcName]; invariant(typeof baseFunc === "function", "Base function not defined on Array prototype: '" + funcName + "'"); addHiddenProp(ObservableArray.prototype, funcName, function () { this.$mobx.atom.reportObserved(); return baseFunc.apply(this.$mobx.values, arguments); }); }); var ENTRY_0 = { configurable: true, enumerable: false, set: createArraySetter(0), get: createArrayGetter(0) }; function createArrayBufferItem(index) { var set = createArraySetter(index); var get = createArrayGetter(index); Object.defineProperty(ObservableArray.prototype, "" + index, { enumerable: false, configurable: true, set: set, get: get }); } function createArraySetter(index) { return function (newValue) { var adm = this.$mobx; var values = adm.values; assertUnwrapped(newValue, "Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."); if (index < values.length) { checkIfStateModificationsAreAllowed(); var oldValue = values[index]; if (hasInterceptors(adm)) { var change = interceptChange(adm, { type: "update", object: adm.array, index: index, newValue: newValue }); if (!change) { return; } newValue = change.newValue; } newValue = adm.makeReactiveArrayItem(newValue); var changed = (adm.mode === ValueMode.Structure) ? !deepEquals(oldValue, newValue) : oldValue !== newValue; if (changed) { values[index] = newValue; adm.notifyArrayChildUpdate(index, newValue, oldValue); } } else if (index === values.length) { adm.spliceWithArray(index, 0, [newValue]); } else { throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length); } }; } function createArrayGetter(index) { return function () { var impl = this.$mobx; if (impl && index < impl.values.length) { impl.atom.reportObserved(); return impl.values[index]; } console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + impl.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); return undefined; }; } function reserveArrayBuffer(max) { for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++) { createArrayBufferItem(index); } OBSERVABLE_ARRAY_BUFFER_SIZE = max; } reserveArrayBuffer(1000); function createObservableArray(initialValues, mode, name) { return new ObservableArray(initialValues, mode, name); } function fastArray(initialValues) { deprecated("fastArray is deprecated. Please use `observable(asFlat([]))`"); return createObservableArray(initialValues, ValueMode.Flat, null); } exports.fastArray = fastArray; var isObservableArrayAdministration = createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); function isObservableArray(thing) { return isObject(thing) && isObservableArrayAdministration(thing.$mobx); } exports.isObservableArray = isObservableArray; var ObservableMapMarker = {}; var ObservableMap = (function () { function ObservableMap(initialData, valueModeFunc) { var _this = this; this.$mobx = ObservableMapMarker; this._data = {}; this._hasMap = {}; this.name = "ObservableMap@" + getNextId(); this._keys = new ObservableArray(null, ValueMode.Reference, this.name + ".keys()", true); this.interceptors = null; this.changeListeners = null; this._valueMode = getValueModeFromModifierFunc(valueModeFunc); if (this._valueMode === ValueMode.Flat) { this._valueMode = ValueMode.Reference; } allowStateChanges(true, function () { if (isPlainObject(initialData)) { _this.merge(initialData); } else if (Array.isArray(initialData)) { initialData.forEach(function (_a) { var key = _a[0], value = _a[1]; return _this.set(key, value); }); } }); } ObservableMap.prototype._has = function (key) { return typeof this._data[key] !== "undefined"; }; ObservableMap.prototype.has = function (key) { if (!this.isValidKey(key)) { return false; } key = "" + key; if (this._hasMap[key]) { return this._hasMap[key].get(); } return this._updateHasMapEntry(key, false).get(); }; ObservableMap.prototype.set = function (key, value) { this.assertValidKey(key); key = "" + key; var hasKey = this._has(key); assertUnwrapped(value, "[mobx.map.set] Expected unwrapped value to be inserted to key '" + key + "'. If you need to use modifiers pass them as second argument to the constructor"); if (hasInterceptors(this)) { var change = interceptChange(this, { type: hasKey ? "update" : "add", object: this, newValue: value, name: key }); if (!change) { return; } value = change.newValue; } if (hasKey) { this._updateValue(key, value); } else { this._addValue(key, value); } }; ObservableMap.prototype.delete = function (key) { var _this = this; this.assertValidKey(key); key = "" + key; if (hasInterceptors(this)) { var change = interceptChange(this, { type: "delete", object: this, name: key }); if (!change) { return false; } } if (this._has(key)) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "delete", object: this, oldValue: this._data[key].value, name: key } : null; if (notifySpy) { spyReportStart(change); } transaction(function () { _this._keys.remove(key); _this._updateHasMapEntry(key, false); var observable = _this._data[key]; observable.setNewValue(undefined); _this._data[key] = undefined; }, undefined, false); if (notify) { notifyListeners(this, change); } if (notifySpy) { spyReportEnd(); } return true; } return false; }; ObservableMap.prototype._updateHasMapEntry = function (key, value) { var entry = this._hasMap[key]; if (entry) { entry.setNewValue(value); } else { entry = this._hasMap[key] = new ObservableValue(value, ValueMode.Reference, this.name + "." + key + "?", false); } return entry; }; ObservableMap.prototype._updateValue = function (name, newValue) { var observable = this._data[name]; newValue = observable.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "update", object: this, oldValue: observable.value, name: name, newValue: newValue } : null; if (notifySpy) { spyReportStart(change); } observable.setNewValue(newValue); if (notify) { notifyListeners(this, change); } if (notifySpy) { spyReportEnd(); } } }; ObservableMap.prototype._addValue = function (name, newValue) { var _this = this; transaction(function () { var observable = _this._data[name] = new ObservableValue(newValue, _this._valueMode, _this.name + "." + name, false); newValue = observable.value; _this._updateHasMapEntry(name, true); _this._keys.push(name); }, undefined, false); var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "add", object: this, name: name, newValue: newValue } : null; if (notifySpy) { spyReportStart(change); } if (notify) { notifyListeners(this, change); } if (notifySpy) { spyReportEnd(); } }; ObservableMap.prototype.get = function (key) { key = "" + key; if (this.has(key)) { return this._data[key].get(); } return undefined; }; ObservableMap.prototype.keys = function () { return arrayAsIterator(this._keys.slice()); }; ObservableMap.prototype.values = function () { return arrayAsIterator(this._keys.map(this.get, this)); }; ObservableMap.prototype.entries = function () { var _this = this; return arrayAsIterator(this._keys.map(function (key) { return [key, _this.get(key)]; })); }; ObservableMap.prototype.forEach = function (callback, thisArg) { var _this = this; this.keys().forEach(function (key) { return callback.call(thisArg, _this.get(key), key); }); }; ObservableMap.prototype.merge = function (other) { var _this = this; transaction(function () { if (isObservableMap(other)) { other.keys().forEach(function (key) { return _this.set(key, other.get(key)); }); } else { Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); }); } }, undefined, false); return this; }; ObservableMap.prototype.clear = function () { var _this = this; transaction(function () { untracked(function () { _this.keys().forEach(_this.delete, _this); }); }, undefined, false); }; Object.defineProperty(ObservableMap.prototype, "size", { get: function () { return this._keys.length; }, enumerable: true, configurable: true }); ObservableMap.prototype.toJS = function () { var _this = this; var res = {}; this.keys().forEach(function (key) { return res[key] = _this.get(key); }); return res; }; ObservableMap.prototype.toJs = function () { deprecated("toJs is deprecated, use toJS instead"); return this.toJS(); }; ObservableMap.prototype.toJSON = function () { return this.toJS(); }; ObservableMap.prototype.isValidKey = function (key) { if (key === null || key === undefined) { return false; } if (typeof key !== "string" && typeof key !== "number" && typeof key !== "boolean") { return false; } return true; }; ObservableMap.prototype.assertValidKey = function (key) { if (!this.isValidKey(key)) { throw new Error("[mobx.map] Invalid key: '" + key + "'"); } }; ObservableMap.prototype.toString = function () { var _this = this; return this.name + "[{ " + this.keys().map(function (key) { return (key + ": " + ("" + _this.get(key))); }).join(", ") + " }]"; }; ObservableMap.prototype.observe = function (listener, fireImmediately) { invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable maps."); return registerListener(this, listener); }; ObservableMap.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; return ObservableMap; }()); exports.ObservableMap = ObservableMap; declareIterator(ObservableMap.prototype, function () { return this.entries(); }); function map(initialValues, valueModifier) { return new ObservableMap(initialValues, valueModifier); } exports.map = map; var isObservableMap = createInstanceofPredicate("ObservableMap", ObservableMap); exports.isObservableMap = isObservableMap; var ObservableObjectAdministration = (function () { function ObservableObjectAdministration(target, name, mode) { this.target = target; this.name = name; this.mode = mode; this.values = {}; this.changeListeners = null; this.interceptors = null; } ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) { invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects."); return registerListener(this, callback); }; ObservableObjectAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; return ObservableObjectAdministration; }()); function asObservableObject(target, name, mode) { if (mode === void 0) { mode = ValueMode.Recursive; } if (isObservableObject(target)) { return target.$mobx; } if (!isPlainObject(target)) { name = target.constructor.name + "@" + getNextId(); } if (!name) { name = "ObservableObject@" + getNextId(); } var adm = new ObservableObjectAdministration(target, name, mode); addHiddenFinalProp(target, "$mobx", adm); return adm; } function setObservableObjectInstanceProperty(adm, propName, descriptor) { if (adm.values[propName]) { invariant("value" in descriptor, "cannot redefine property " + propName); adm.target[propName] = descriptor.value; } else { if ("value" in descriptor) { defineObservableProperty(adm, propName, descriptor.value, true, undefined); } else { defineObservableProperty(adm, propName, descriptor.get, true, descriptor.set); } } } function defineObservableProperty(adm, propName, newValue, asInstanceProperty, setter) { if (asInstanceProperty) { assertPropertyConfigurable(adm.target, propName); } var observable; var name = adm.name + "." + propName; var isComputed = true; if (isComputedValue(newValue)) { observable = newValue; newValue.name = name; if (!newValue.scope) { newValue.scope = adm.target; } } else if (typeof newValue === "function" && newValue.length === 0 && !isAction(newValue)) { observable = new ComputedValue(newValue, adm.target, false, name, setter); } else if (getModifier(newValue) === ValueMode.Structure && typeof newValue.value === "function" && newValue.value.length === 0) { observable = new ComputedValue(newValue.value, adm.target, true, name, setter); } else { isComputed = false; if (hasInterceptors(adm)) { var change = interceptChange(adm, { object: adm.target, name: propName, type: "add", newValue: newValue }); if (!change) { return; } newValue = change.newValue; } observable = new ObservableValue(newValue, adm.mode, name, false); newValue = observable.value; } adm.values[propName] = observable; if (asInstanceProperty) { Object.defineProperty(adm.target, propName, isComputed ? generateComputedPropConfig(propName) : generateObservablePropConfig(propName)); } if (!isComputed) { notifyPropertyAddition(adm, adm.target, propName, newValue); } } var observablePropertyConfigs = {}; var computedPropertyConfigs = {}; function generateObservablePropConfig(propName) { var config = observablePropertyConfigs[propName]; if (config) { return config; } return observablePropertyConfigs[propName] = { configurable: true, enumerable: true, get: function () { return this.$mobx.values[propName].get(); }, set: function (v) { setPropertyValue(this, propName, v); } }; } function generateComputedPropConfig(propName) { var config = computedPropertyConfigs[propName]; if (config) { return config; } return computedPropertyConfigs[propName] = { configurable: true, enumerable: false, get: function () { return this.$mobx.values[propName].get(); }, set: function (v) { return this.$mobx.values[propName].set(v); } }; } function setPropertyValue(instance, name, newValue) { var adm = instance.$mobx; var observable = adm.values[name]; if (hasInterceptors(adm)) { var change = interceptChange(adm, { type: "update", object: instance, name: name, newValue: newValue }); if (!change) { return; } newValue = change.newValue; } newValue = observable.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notify = hasListeners(adm); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "update", object: instance, oldValue: observable.value, name: name, newValue: newValue } : null; if (notifySpy) { spyReportStart(change); } observable.setNewValue(newValue); if (notify) { notifyListeners(adm, change); } if (notifySpy) { spyReportEnd(); } } } function notifyPropertyAddition(adm, object, name, newValue) { var notify = hasListeners(adm); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "add", object: object, name: name, newValue: newValue } : null; if (notifySpy) { spyReportStart(change); } if (notify) { notifyListeners(adm, change); } if (notifySpy) { spyReportEnd(); } } var isObservableObjectAdministration = createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); function isObservableObject(thing) { if (isObject(thing)) { runLazyInitializers(thing); return isObservableObjectAdministration(thing.$mobx); } return false; } exports.isObservableObject = isObservableObject; var UNCHANGED = {}; var ObservableValue = (function (_super) { __extends(ObservableValue, _super); function ObservableValue(value, mode, name, notifySpy) { if (name === void 0) { name = "ObservableValue@" + getNextId(); } if (notifySpy === void 0) { notifySpy = true; } _super.call(this, name); this.mode = mode; this.hasUnreportedChange = false; this.value = undefined; var _a = getValueModeFromValue(value, ValueMode.Recursive), childmode = _a[0], unwrappedValue = _a[1]; if (this.mode === ValueMode.Recursive) { this.mode = childmode; } this.value = makeChildObservable(unwrappedValue, this.mode, this.name); if (notifySpy && isSpyEnabled()) { spyReport({ type: "create", object: this, newValue: this.value }); } } ObservableValue.prototype.set = function (newValue) { var oldValue = this.value; newValue = this.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notifySpy = isSpyEnabled(); if (notifySpy) { spyReportStart({ type: "update", object: this, newValue: newValue, oldValue: oldValue }); } this.setNewValue(newValue); if (notifySpy) { spyReportEnd(); } } }; ObservableValue.prototype.prepareNewValue = function (newValue) { assertUnwrapped(newValue, "Modifiers cannot be used on non-initial values."); checkIfStateModificationsAreAllowed(); if (hasInterceptors(this)) { var change = interceptChange(this, { object: this, type: "update", newValue: newValue }); if (!change) { return UNCHANGED; } newValue = change.newValue; } var changed = valueDidChange(this.mode === ValueMode.Structure, this.value, newValue); if (changed) { return makeChildObservable(newValue, this.mode, this.name); } return UNCHANGED; }; ObservableValue.prototype.setNewValue = function (newValue) { var oldValue = this.value; this.value = newValue; this.reportChanged(); if (hasListeners(this)) { notifyListeners(this, [newValue, oldValue]); } }; ObservableValue.prototype.get = function () { this.reportObserved(); return this.value; }; ObservableValue.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableValue.prototype.observe = function (listener, fireImmediately) { if (fireImmediately) { listener(this.value, undefined); } return registerListener(this, listener); }; ObservableValue.prototype.toJSON = function () { return this.get(); }; ObservableValue.prototype.toString = function () { return this.name + "[" + this.value + "]"; }; return ObservableValue; }(BaseAtom)); var isObservableValue = createInstanceofPredicate("ObservableValue", ObservableValue); function getAtom(thing, property) { if (typeof thing === "object" && thing !== null) { if (isObservableArray(thing)) { invariant(property === undefined, "It is not possible to get index atoms from arrays"); return thing.$mobx.atom; } if (isObservableMap(thing)) { if (property === undefined) { return getAtom(thing._keys); } var observable_2 = thing._data[property] || thing._hasMap[property]; invariant(!!observable_2, "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'"); return observable_2; } runLazyInitializers(thing); if (isObservableObject(thing)) { invariant(!!property, "please specify a property"); var observable_3 = thing.$mobx.values[property]; invariant(!!observable_3, "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'"); return observable_3; } if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { return thing; } } else if (typeof thing === "function") { if (isReaction(thing.$mobx)) { return thing.$mobx; } } invariant(false, "Cannot obtain atom from " + thing); } function getAdministration(thing, property) { invariant(thing, "Expecting some object"); if (property !== undefined) { return getAdministration(getAtom(thing, property)); } if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { return thing; } if (isObservableMap(thing)) { return thing; } runLazyInitializers(thing); if (thing.$mobx) { return thing.$mobx; } invariant(false, "Cannot obtain administration from " + thing); } function getDebugName(thing, property) { var named; if (property !== undefined) { named = getAtom(thing, property); } else if (isObservableObject(thing) || isObservableMap(thing)) { named = getAdministration(thing); } else { named = getAtom(thing); } return named.name; } function createClassPropertyDecorator(onInitialize, get, set, enumerable, allowCustomArguments) { function classPropertyDecorator(target, key, descriptor, customArgs, argLen) { invariant(allowCustomArguments || quacksLikeADecorator(arguments), "This function is a decorator, but it wasn't invoked like a decorator"); if (!descriptor) { var newDescriptor = { enumerable: enumerable, configurable: true, get: function () { if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) { typescriptInitializeProperty(this, key, undefined, onInitialize, customArgs, descriptor); } return get.call(this, key); }, set: function (v) { if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) { typescriptInitializeProperty(this, key, v, onInitialize, customArgs, descriptor); } else { set.call(this, key, v); } } }; if (arguments.length < 3 || arguments.length === 5 && argLen < 3) { Object.defineProperty(target, key, newDescriptor); } return newDescriptor; } else { if (!hasOwnProperty(target, "__mobxLazyInitializers")) { addHiddenProp(target, "__mobxLazyInitializers", (target.__mobxLazyInitializers && target.__mobxLazyInitializers.slice()) || []); } var value_1 = descriptor.value, initializer_1 = descriptor.initializer; target.__mobxLazyInitializers.push(function (instance) { onInitialize(instance, key, (initializer_1 ? initializer_1.call(instance) : value_1), customArgs, descriptor); }); return { enumerable: enumerable, configurable: true, get: function () { if (this.__mobxDidRunLazyInitializers !== true) { runLazyInitializers(this); } return get.call(this, key); }, set: function (v) { if (this.__mobxDidRunLazyInitializers !== true) { runLazyInitializers(this); } set.call(this, key, v); } }; } } if (allowCustomArguments) { return function () { if (quacksLikeADecorator(arguments)) { return classPropertyDecorator.apply(null, arguments); } var outerArgs = arguments; var argLen = arguments.length; return function (target, key, descriptor) { return classPropertyDecorator(target, key, descriptor, outerArgs, argLen); }; }; } return classPropertyDecorator; } function typescriptInitializeProperty(instance, key, v, onInitialize, customArgs, baseDescriptor) { if (!hasOwnProperty(instance, "__mobxInitializedProps")) { addHiddenProp(instance, "__mobxInitializedProps", {}); } instance.__mobxInitializedProps[key] = true; onInitialize(instance, key, v, customArgs, baseDescriptor); } function runLazyInitializers(instance) { if (instance.__mobxDidRunLazyInitializers === true) { return; } if (instance.__mobxLazyInitializers) { addHiddenProp(instance, "__mobxDidRunLazyInitializers", true); instance.__mobxDidRunLazyInitializers && instance.__mobxLazyInitializers.forEach(function (initializer) { return initializer(instance); }); } } function quacksLikeADecorator(args) { return (args.length === 2 || args.length === 3) && typeof args[1] === "string"; } function iteratorSymbol() { return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator"; } var IS_ITERATING_MARKER = "__$$iterating"; function arrayAsIterator(array) { invariant(array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator"); addHiddenFinalProp(array, IS_ITERATING_MARKER, true); var idx = -1; addHiddenFinalProp(array, "next", function next() { idx++; return { done: idx >= this.length, value: idx < this.length ? this[idx] : undefined }; }); return array; } function declareIterator(prototType, iteratorFactory) { addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory); } var SimpleEventEmitter = (function () { function SimpleEventEmitter() { this.listeners = []; deprecated("extras.SimpleEventEmitter is deprecated and will be removed in the next major release"); } SimpleEventEmitter.prototype.emit = function () { var arguments$1 = arguments; var listeners = this.listeners.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(null, arguments$1); } }; SimpleEventEmitter.prototype.on = function (listener) { var _this = this; this.listeners.push(listener); return once(function () { var idx = _this.listeners.indexOf(listener); if (idx !== -1) { _this.listeners.splice(idx, 1); } }); }; SimpleEventEmitter.prototype.once = function (listener) { var subscription = this.on(function () { subscription(); listener.apply(this, arguments); }); return subscription; }; return SimpleEventEmitter; }()); exports.SimpleEventEmitter = SimpleEventEmitter; var EMPTY_ARRAY = []; Object.freeze(EMPTY_ARRAY); function getNextId() { return ++globalState.mobxGuid; } function invariant(check, message, thing) { if (!check) { throw new Error("[mobx] Invariant failed: " + message + (thing ? " in '" + thing + "'" : "")); } } var deprecatedMessages = []; function deprecated(msg) { if (deprecatedMessages.indexOf(msg) !== -1) { return; } deprecatedMessages.push(msg); console.error("[mobx] Deprecated: " + msg); } function once(func) { var invoked = false; return function () { if (invoked) { return; } invoked = true; return func.apply(this, arguments); }; } var noop = function () { }; function unique(list) { var res = []; list.forEach(function (item) { if (res.indexOf(item) === -1) { res.push(item); } }); return res; } function joinStrings(things, limit, separator) { if (limit === void 0) { limit = 100; } if (separator === void 0) { separator = " - "; } if (!things) { return ""; } var sliced = things.slice(0, limit); return "" + sliced.join(separator) + (things.length > limit ? " (... and " + (things.length - limit) + "more)" : ""); } function isObject(value) { return value !== null && typeof value === "object"; } function isPlainObject(value) { if (value === null || typeof value !== "object") { return false; } var proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; } function objectAssign() { var arguments$1 = arguments; var res = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var source = arguments$1[i]; for (var key in source) { if (hasOwnProperty(source, key)) { res[key] = source[key]; } } } return res; } function valueDidChange(compareStructural, oldValue, newValue) { return compareStructural ? !deepEquals(oldValue, newValue) : oldValue !== newValue; } var prototypeHasOwnProperty = Object.prototype.hasOwnProperty; function hasOwnProperty(object, propName) { return prototypeHasOwnProperty.call(object, propName); } function makeNonEnumerable(object, propNames) { for (var i = 0; i < propNames.length; i++) { addHiddenProp(object, propNames[i], object[propNames[i]]); } } function addHiddenProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: true, configurable: true, value: value }); } function addHiddenFinalProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: false, configurable: true, value: value }); } function isPropertyConfigurable(object, prop) { var descriptor = Object.getOwnPropertyDescriptor(object, prop); return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false); } function assertPropertyConfigurable(object, prop) { invariant(isPropertyConfigurable(object, prop), "Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object"); } function getEnumerableKeys(obj) { var res = []; for (var key in obj) { res.push(key); } return res; } function deepEquals(a, b) { if (a === null && b === null) { return true; } if (a === undefined && b === undefined) { return true; } var aIsArray = isArrayLike(a); if (aIsArray !== isArrayLike(b)) { return false; } else if (aIsArray) { if (a.length !== b.length) { return false; } for (var i = a.length - 1; i >= 0; i--) { if (!deepEquals(a[i], b[i])) { return false; } } return true; } else if (typeof a === "object" && typeof b === "object") { if (a === null || b === null) { return false; } if (getEnumerableKeys(a).length !== getEnumerableKeys(b).length) { return false; } for (var prop in a) { if (!(prop in b)) { return false; } if (!deepEquals(a[prop], b[prop])) { return false; } } return true; } return a === b; } function createInstanceofPredicate(name, clazz) { var propName = "isMobX" + name; clazz.prototype[propName] = true; return function (x) { return isObject(x) && x[propName] === true; }; } function isArrayLike(x) { return Array.isArray(x) || isObservableArray(x); } exports.isArrayLike = isArrayLike; }); var Reaction = mobx.Reaction; var isObservable = mobx.isObservable; var extras = mobx.extras; var EventEmitter = function EventEmitter() { this.listeners = []; }; EventEmitter.prototype.on = function on (cb) { var this$1 = this; this.listeners.push(cb); return function () { var index = this$1.listeners.indexOf(cb); if (index !== -1) { this$1.listeners.splice(index, 1); } }; }; EventEmitter.prototype.emit = function emit (data) { this.listeners.forEach(function (fn) { return fn(data); }); }; EventEmitter.prototype.getTotalListeners = function getTotalListeners () { return this.listeners.length; }; EventEmitter.prototype.clearListeners = function clearListeners () { this.listeners = []; }; var findDOMNode = Inferno.findDOMNode; /** * Dev tools support */ var isDevtoolsEnabled = false; var componentByNodeRegistery = new WeakMap(); var renderReporter = new EventEmitter(); function reportRendering(component) { var node = findDOMNode(component); if (node && componentByNodeRegistery) { componentByNodeRegistery.set(node, component); } renderReporter.emit({ event: 'render', renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart, component: component, node: node }); } function trackComponents() { if (typeof WeakMap === 'undefined') { throwError('[inferno-mobx] tracking components is not supported in this browser.'); } if (!isDevtoolsEnabled) { isDevtoolsEnabled = true; } } function makeReactive(componentClass) { var target = componentClass.prototype || componentClass; var baseDidMount = target.componentDidMount; var baseWillMount = target.componentWillMount; var baseUnmount = target.componentWillUnmount; target.componentWillMount = function () { var this$1 = this; // Call original baseWillMount && baseWillMount.call(this); var reaction$$1; var isRenderingPending = false; var initialName = this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || "<component>"; var baseRender = this.render.bind(this); var initialRender = function (nextProps, nextContext) { reaction$$1 = new Reaction((initialName + ".render()"), function () { if (!isRenderingPending) { isRenderingPending = true; if (this$1.__$mobxIsUnmounted !== true) { var hasError = true; try { Component.prototype.forceUpdate.call(this$1); hasError = false; } finally { if (hasError) { reaction$$1.dispose(); } } } } }); reactiveRender.$mobx = reaction$$1; this$1.render = reactiveRender; return reactiveRender(nextProps, nextContext); }; var reactiveRender = function (nextProps, nextContext) { isRenderingPending = false; var rendering = undefined; reaction$$1.track(function () { if (isDevtoolsEnabled) { this$1.__$mobRenderStart = Date.now(); } rendering = extras.allowStateChanges(false, baseRender.bind(this$1, nextProps, nextContext)); if (isDevtoolsEnabled) { this$1.__$mobRenderEnd = Date.now(); } }); return rendering; }; this.render = initialRender; }; target.componentDidMount = function () { isDevtoolsEnabled && reportRendering(this); // Call original baseDidMount && baseDidMount.call(this); }; target.componentWillUnmount = function () { // Call original baseUnmount && baseUnmount.call(this); // Dispose observables this.render.$mobx && this.render.$mobx.dispose(); this.__$mobxIsUnmounted = true; if (isDevtoolsEnabled) { var node = findDOMNode(this); if (node && componentByNodeRegistery) { componentByNodeRegistery.delete(node); } renderReporter.emit({ event: 'destroy', component: this, node: node }); } }; target.shouldComponentUpdate = function (nextProps, nextState) { var this$1 = this; // Update on any state changes (as is the default) if (this.state !== nextState) { return true; } // Update if props are shallowly not equal, inspired by PureRenderMixin var keys = Object.keys(this.props); if (keys.length !== Object.keys(nextProps).length) { return true; } for (var i = keys.length - 1; i >= 0; i--) { var key = keys[i]; var newValue = nextProps[key]; if (newValue !== this$1.props[key]) { return true; } else if (newValue && typeof newValue === 'object' && !isObservable(newValue)) { // If the newValue is still the same object, but that object is not observable, // fallback to the default behavior: update, because the object *might* have changed. return true; } } return true; }; return componentClass; } var index$1 = createCommonjsModule(function (module) { 'use strict'; var INFERNO_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!INFERNO_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) { } } } } return targetComponent; } module.exports = hoistNonReactStatics; module.exports.default = module.exports; }); /** * Store Injection */ function createStoreInjector(grabStoresFn, component) { var Injector = createClass({ displayName: component.name, render: function render() { var this$1 = this; var newProps = {}; for (var key in this.props) { if (this$1.props.hasOwnProperty(key)) { newProps[key] = this$1.props[key]; } } var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {}; for (var key$1 in additionalProps) { newProps[key$1] = additionalProps[key$1]; } newProps.ref = function (instance) { this$1.wrappedInstance = instance; }; return createElement(component, newProps); } }); Injector.contextTypes = { mobxStores: function mobxStores() { } }; index$1(Injector, component); return Injector; } var grabStoresByName = function (storeNames) { return function (baseStores, nextProps) { storeNames.forEach(function (storeName) { // Prefer props over stores if (storeName in nextProps) { return; } if (!(storeName in baseStores)) { throw new Error("MobX observer: Store \"" + storeName + "\" is not available! " + "Make sure it is provided by some Provider"); } nextProps[storeName] = baseStores[storeName]; }); return nextProps; }; }; /** * Higher order component that injects stores to a child. * takes either a varargs list of strings, which are stores read from the context, * or a function that manually maps the available stores from the context to props: * storesToProps(mobxStores, props, context) => newProps */ function inject(grabStoresFn) { var arguments$1 = arguments; if (typeof grabStoresFn !== 'function') { var storesNames = []; for (var i = 0; i < arguments.length; i++) { storesNames[i] = arguments$1[i]; } grabStoresFn = grabStoresByName(storesNames); } return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass); }; } /** * Wraps a component and provides stores as props */ function connect(arg1, arg2) { if ( arg2 === void 0 ) arg2 = null; if (typeof arg1 === 'string') { throwError('Store names should be provided as array'); } if (Array.isArray(arg1)) { // component needs stores if (!arg2) { // invoked as decorator return function (componentClass) { return connect(arg1, componentClass); }; } else { // TODO: deprecate this invocation style return inject.apply(null, arg1)(connect(arg2)); } } var componentClass = arg1; // Stateless function component: // If it is function but doesn't seem to be a Inferno class constructor, // wrap it to a Inferno class automatically if (typeof componentClass === 'function' && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !Component.isPrototypeOf(componentClass)) { var newClass = createClass({ displayName: componentClass.displayName || componentClass.name, propTypes: componentClass.propTypes, contextTypes: componentClass.contextTypes, getDefaultProps: function () { return componentClass.defaultProps; }, render: function render() { return componentClass.call(this, this.props, this.context); } }); return connect(newClass); } if (!componentClass) { throwError('Please pass a valid component to "observer"'); } componentClass.isMobXReactObserver = true; return makeReactive(componentClass); } var index = { Provider: Provider, inject: inject, connect: connect, observer: connect, trackComponents: trackComponents, renderReporter: renderReporter, componentByNodeRegistery: componentByNodeRegistery }; return index; })));
src/svg-icons/action/description.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDescription = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/> </SvgIcon> ); ActionDescription = pure(ActionDescription); ActionDescription.displayName = 'ActionDescription'; export default ActionDescription;
spec/javascripts/jsx/speed_grader/AssessmentAuditTray/components/AssessmentSummarySpec.js
djbender/canvas-lms
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import timezone from 'timezone' import newYork from 'timezone/America/New_York' import AssessmentSummary from 'jsx/speed_grader/AssessmentAuditTray/components/AssessmentSummary' import {overallAnonymityStates} from 'jsx/speed_grader/AssessmentAuditTray/AuditTrailHelpers' const {FULL, NA, PARTIAL} = overallAnonymityStates QUnit.module('AssessmentSummary', suiteHooks => { let $container let props let timezoneSnapshot suiteHooks.beforeEach(() => { $container = document.body.appendChild(document.createElement('div')) timezoneSnapshot = timezone.snapshot() timezone.changeZone(newYork, 'America/New_York') props = { anonymityDate: new Date('2015-04-04T19:00:00.000Z'), assignment: { gradesPublishedAt: '2015-05-04T16:00:00.000Z', pointsPossible: 10 }, finalGradeDate: new Date('2015-04-18T17:00:00.000Z'), overallAnonymity: FULL, submission: { score: 9.5 } } }) suiteHooks.afterEach(() => { ReactDOM.unmountComponentAtNode($container) $container.remove() timezone.restore(timezoneSnapshot) }) function renderComponent() { ReactDOM.render(<AssessmentSummary {...props} />, $container) } QUnit.module('"Final Grade"', () => { test('shows the score out of points possible', () => { renderComponent() ok($container.textContent.includes('9.5/10')) }) test('rounds the score to two decimal places', () => { props.submission.score = 9.523 renderComponent() ok($container.textContent.includes('9.52/10')) }) test('rounds the points possible to two decimal places', () => { props.assignment.pointsPossible = 10.017 renderComponent() ok($container.textContent.includes('9.5/10.02')) }) test('displays zero out of points possible when the score is zero', () => { props.submission.score = 0 renderComponent() ok($container.textContent.includes('0/10')) }) test('displays score out of zero points possible when the assignment is worth zero points', () => { props.assignment.pointsPossible = 0 renderComponent() ok($container.textContent.includes('9.5/0')) }) test('displays "–" (en dash) for score when the submission is ungraded', () => { props.submission.score = null renderComponent() ok($container.textContent.includes('–/10')) }) test('displays the "final grade" date from the audit trail', () => { renderComponent() const $time = $container.querySelector('#audit-tray-final-grade time') equal($time.getAttribute('datetime'), '2015-04-18T17:00:00.000Z') }) test('includes the time on the visible date', () => { renderComponent() const $time = $container.querySelector('#audit-tray-final-grade time') ok($time.textContent.includes('1pm')) }) }) QUnit.module('"Posted to student"', () => { test('displays the "grades published" date from the assignment', () => { renderComponent() const $time = $container.querySelector('#audit-tray-grades-posted time') equal($time.getAttribute('datetime'), props.assignment.gradesPublishedAt) }) test('includes the time on the visible date', () => { renderComponent() const $time = $container.querySelector('#audit-tray-grades-posted time') ok($time.textContent.includes('12pm')) }) }) QUnit.module('"Overall Anonymity"', () => { let $description let $label function getOverallAnonymityLabel() { return $container.querySelector('#audit-tray-overall-anonymity-label') } function getOverallAnonymityDescription() { return $container.querySelector('#audit-tray-overall-anonymity-description') } function renderAndQuery() { renderComponent() $label = getOverallAnonymityLabel() $description = getOverallAnonymityDescription() } QUnit.module('when anonymity was used without interruption', contextHooks => { contextHooks.beforeEach(() => { props.overallAnonymity = FULL renderAndQuery() }) test('labels the indicator with "Anonymous On"', () => { equal($label.textContent, 'Anonymous On') }) test('displays the anonymity date', () => { const $time = $description.querySelector('time') equal($time.getAttribute('datetime'), '2015-04-04T19:00:00.000Z') }) test('includes the time on the visible date', () => { const $time = $description.querySelector('time') ok($time.textContent.includes('3pm')) }) }) QUnit.module('when anonymity was applied multiple times', contextHooks => { contextHooks.beforeEach(() => { props.overallAnonymity = PARTIAL renderAndQuery() }) test('labels the indicator with "Partially Anonymous"', () => { // TODO: Swap the assertion here for GRADE-1820 // equal($label.textContent, 'Partially Anonymous') ok($label.textContent.includes('Partially')) }) test('displays the anonymity date', () => { const $time = $description.querySelector('time') equal($time.getAttribute('datetime'), '2015-04-04T19:00:00.000Z') }) test('includes the time on the visible date', () => { const $time = $description.querySelector('time') ok($time.textContent.includes('3pm')) }) }) QUnit.module('when anonymity was not used', contextHooks => { contextHooks.beforeEach(() => { props.anonymityDate = null props.overallAnonymity = NA renderAndQuery() }) test('labels the indicator with "Anonymous Off"', () => { equal($label.textContent, 'Anonymous Off') }) test('includes the time on the visible date', () => { equal($description.textContent, 'Anonymous was never turned on') }) }) }) })
src/components/foiRequests/WebView/index.js
jfilter/frag-den-staat-app
import { Platform, Share } from 'react-native'; import { WebView } from 'react-native-webview'; import React from 'react'; import NavBarIcon from '../NavBarIcon'; const FoiRequestsWebView = ({ navigation }) => ( <WebView source={{ uri: navigation.state.params.uri }} /> ); FoiRequestsWebView.navigationOptions = props => { const url = props.navigation.state.params.uri; function share() { Share.share( { ...Platform.select({ ios: { url, }, android: { message: url, }, }), title: 'FragDenStaat', }, { ...Platform.select({ android: { // Android only: dialogTitle: `Share: ${url}`, }, }), } ); } let iconName = 'share'; let iconType = 'material'; // platform specific share button if (Platform.OS === 'ios') { iconName = 'ios-share'; iconType = 'ionicon'; } return { title: 'Browser-Ansicht', tabBarVisible: false, headerRight: ( <NavBarIcon iconName={iconName} iconType={iconType} onPress={share} /> ), }; }; export default FoiRequestsWebView;
ajax/libs/react-router/0.11.0/react-router.min.js
shelsonjava/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:position?window.scrollTo(position.x,position.y):window.scrollTo(0,0)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),DefaultRoute=React.createClass({displayName:"DefaultRoute",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:PropTypes.falsy,handler:React.PropTypes.func.isRequired}});module.exports=DefaultRoute},{"../mixins/FakeNode":13,"../utils/PropTypes":21}],4:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,classSet=_dereq_("react/lib/cx"),assign=_dereq_("react/lib/Object.assign"),Navigation=_dereq_("../mixins/Navigation"),State=_dereq_("../mixins/State"),Link=React.createClass({displayName:"Link",mixins:[Navigation,State],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var classNames={};return this.props.className&&(classNames[this.props.className]=!0),this.isActive(this.props.to,this.props.params,this.props.query)&&(classNames[this.props.activeClassName]=!0),classSet(classNames)},render:function(){var props=assign({},this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/Navigation":14,"../mixins/State":17,"react/lib/Object.assign":36,"react/lib/cx":37}],5:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),NotFoundRoute=React.createClass({displayName:"NotFoundRoute",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:PropTypes.falsy,handler:React.PropTypes.func.isRequired}});module.exports=NotFoundRoute},{"../mixins/FakeNode":13,"../utils/PropTypes":21}],6:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),Redirect=React.createClass({displayName:"Redirect",mixins:[FakeNode],propTypes:{path:React.PropTypes.string,from:React.PropTypes.string,to:React.PropTypes.string,handler:PropTypes.falsy}});module.exports=Redirect},{"../mixins/FakeNode":13,"../utils/PropTypes":21}],7:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),Route=React.createClass({displayName:"Route",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:React.PropTypes.string,handler:React.PropTypes.func.isRequired,ignoreScrollBehavior:React.PropTypes.bool}});module.exports=Route},{"../mixins/FakeNode":13}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,RouteHandler=React.createClass({displayName:"RouteHandler",getDefaultProps:function(){return{ref:"__routeHandler__"}},contextTypes:{getRouteAtDepth:React.PropTypes.func.isRequired,getRouteComponents:React.PropTypes.func.isRequired,routeHandlers:React.PropTypes.array.isRequired},childContextTypes:{routeHandlers:React.PropTypes.array.isRequired},getChildContext:function(){return{routeHandlers:this.context.routeHandlers.concat([this])}},getRouteDepth:function(){return this.context.routeHandlers.length-1},componentDidMount:function(){this._updateRouteComponent()},componentDidUpdate:function(){this._updateRouteComponent()},_updateRouteComponent:function(){var depth=this.getRouteDepth(),components=this.context.getRouteComponents();components[depth]=this.refs[this.props.ref]},render:function(){var route=this.context.getRouteAtDepth(this.getRouteDepth());return route?React.createElement(route.handler,this.props):null}});module.exports=RouteHandler},{}],9:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.RouteHandler=_dereq_("./components/RouteHandler"),exports.HashLocation=_dereq_("./locations/HashLocation"),exports.HistoryLocation=_dereq_("./locations/HistoryLocation"),exports.RefreshLocation=_dereq_("./locations/RefreshLocation"),exports.Navigation=_dereq_("./mixins/Navigation"),exports.State=_dereq_("./mixins/State"),exports.create=_dereq_("./utils/createRouter"),exports.run=_dereq_("./utils/runRouter")},{"./components/DefaultRoute":3,"./components/Link":4,"./components/NotFoundRoute":5,"./components/Redirect":6,"./components/Route":7,"./components/RouteHandler":8,"./locations/HashLocation":10,"./locations/HistoryLocation":11,"./locations/RefreshLocation":12,"./mixins/Navigation":14,"./mixins/State":17,"./utils/createRouter":24,"./utils/runRouter":28}],10:[function(_dereq_,module){function getHashPath(){return invariant(canUseDOM,"getHashPath needs a DOM"),Path.decode(window.location.hash.substr(1))}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function notifyChange(type){var change={path:getHashPath(),type:type};_changeListeners.forEach(function(listener){listener(change)})}function onHashChange(){ensureSlash()&&(notifyChange(_actionType||LocationActions.POP),_actionType=null)}var _actionType,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),Path=_dereq_("../utils/Path"),_changeListeners=[],_isListening=!1,HashLocation={addChangeListener:function(listener){_changeListeners.push(listener),ensureSlash(),_isListening||(window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange),_isListening=!0)},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=Path.encode(path)},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(window.location.pathname+"#"+Path.encode(path))},pop:function(){_actionType=LocationActions.POP,window.history.back()},getCurrentPath:getHashPath,toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../utils/Path":19,"react/lib/ExecutionEnvironment":35,"react/lib/invariant":39}],11:[function(_dereq_,module){function getWindowPath(){return invariant(canUseDOM,"getWindowPath needs a DOM"),Path.decode(window.location.pathname+window.location.search)}function notifyChange(type){var change={path:getWindowPath(),type:type};_changeListeners.forEach(function(listener){listener(change)})}function onPopState(){notifyChange(LocationActions.POP)}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),Path=_dereq_("../utils/Path"),_changeListeners=[],_isListening=!1,HistoryLocation={addChangeListener:function(listener){_changeListeners.push(listener),_isListening||(window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState),_isListening=!0)},push:function(path){window.history.pushState({path:path},"",Path.encode(path)),notifyChange(LocationActions.PUSH)},replace:function(path){window.history.replaceState({path:path},"",Path.encode(path)),notifyChange(LocationActions.REPLACE)},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../utils/Path":19,"react/lib/ExecutionEnvironment":35,"react/lib/invariant":39}],12:[function(_dereq_,module){var HistoryLocation=_dereq_("./HistoryLocation"),Path=_dereq_("../utils/Path"),RefreshLocation={push:function(path){window.location=Path.encode(path)},replace:function(path){window.location.replace(Path.encode(path))},pop:function(){window.history.back()},getCurrentPath:HistoryLocation.getCurrentPath,toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../utils/Path":19,"./HistoryLocation":11}],13:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),FakeNode={render:function(){invariant(!1,"%s elements should not be rendered",this.constructor.displayName)}};module.exports=FakeNode},{"react/lib/invariant":39}],14:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,NavigationContext={childContextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},getChildContext:function(){return{makePath:this.constructor.makePath,makeHref:this.constructor.makeHref,transitionTo:this.constructor.transitionTo,replaceWith:this.constructor.replaceWith,goBack:this.constructor.goBack}}};module.exports=NavigationContext},{}],16:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,getWindowScrollPosition=_dereq_("../utils/getWindowScrollPosition"),Scrolling={componentWillMount:function(){invariant(null==this.getScrollBehavior()||canUseDOM,"Cannot use scroll behavior without a DOM"),this._scrollHistory={}},componentDidMount:function(){this._updateScroll()},componentWillUpdate:function(){this._scrollHistory[this.state.path]=getWindowScrollPosition()},componentDidUpdate:function(){this._updateScroll()},componentWillUnmount:function(){delete this._scrollHistory},getScrollPosition:function(path){return this._scrollHistory[path]||null},_updateScroll:function(){var scrollBehavior=this.getScrollBehavior();scrollBehavior&&scrollBehavior.updateScrollPosition(this.getScrollPosition(this.state.path),this.state.action)}};module.exports=Scrolling},{"../utils/getWindowScrollPosition":26,"react/lib/ExecutionEnvironment":35,"react/lib/invariant":39}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,State={contextTypes:{getCurrentPath:React.PropTypes.func.isRequired,getCurrentRoutes:React.PropTypes.func.isRequired,getCurrentParams:React.PropTypes.func.isRequired,getCurrentQuery:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getPath:function(){return this.context.getCurrentPath()},getRoutes:function(){return this.context.getCurrentRoutes()},getParams:function(){return this.context.getCurrentParams()},getQuery:function(){return this.context.getCurrentQuery()},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=State},{}],18:[function(_dereq_,module){function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,assign=_dereq_("react/lib/Object.assign"),Path=_dereq_("../utils/Path"),StateContext={getCurrentPath:function(){return this.state.path},getCurrentRoutes:function(){return this.state.routes.slice(0)},getCurrentParams:function(){return assign({},this.state.params)},getCurrentQuery:function(){return assign({},this.state.query)},isActive:function(to,params,query){return Path.isAbsolute(to)?to===this.state.path:routeIsActive(this.state.routes,to)&&paramsAreActive(this.state.params,params)&&(null==query||queryIsActive(this.state.query,query))},childContextTypes:{getCurrentPath:React.PropTypes.func.isRequired,getCurrentRoutes:React.PropTypes.func.isRequired,getCurrentParams:React.PropTypes.func.isRequired,getCurrentQuery:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{getCurrentPath:this.getCurrentPath,getCurrentRoutes:this.getCurrentRoutes,getCurrentParams:this.getCurrentParams,getCurrentQuery:this.getCurrentQuery,isActive:this.isActive}}};module.exports=StateContext},{"../utils/Path":19,"react/lib/Object.assign":36}],19:[function(_dereq_,module){function decodePathSegment(string){return decodeURIComponent(string.replace(/\+/g," "))}function encodePathSegment(string){return encodeURIComponent(string).replace(/%20/g,"+")}function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramCompileMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramCompileMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,paramInjectMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,paramInjectTrailingSlashMatcher=/\/\/\?|\/\?/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={decode:function(path){return String(path).split("/").map(decodePathSegment).join("/")},encode:function(path){return String(path).split("/").map(encodePathSegment).join("/")},extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=path.match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramInjectMatcher,function(match,paramName){if(paramName=paramName||"splat","?"!==paramName.slice(-1))invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');else if(paramName=paramName.slice(0,-1),null==params[paramName])return"";var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],segment}).replace(paramInjectTrailingSlashMatcher,"/")},extractQuery:function(path){var match=path.match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path},isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:30,"qs/lib/utils":34,"react/lib/invariant":39}],20:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":41}],21:[function(_dereq_,module){var PropTypes={falsy:function(props,propName,elementName){return props[propName]?new Error("<"+elementName+'> may not have a "'+propName+'" prop'):void 0}};module.exports=PropTypes},{}],22:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],23:[function(_dereq_,module){function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function runTransitionFromHooks(transition,routes,components,callback){components=reversedArray(components);var hooks=reversedArray(routes).map(function(route,index){return function(){var handler=route.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,components[index]);var promise=transition._promise;return transition._promise=null,promise}});runHooks(hooks,callback)}function runTransitionToHooks(transition,routes,params,query,callback){var hooks=routes.map(function(route){return function(){var handler=route.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,params,query);var promise=transition._promise;return transition._promise=null,promise}});runHooks(hooks,callback)}function Transition(path,retry){this.path=path,this.abortReason=null,this.isAborted=!1,this.retry=retry.bind(this),this._promise=null}var assign=_dereq_("react/lib/Object.assign"),reversedArray=_dereq_("./reversedArray"),Redirect=_dereq_("./Redirect"),Promise=_dereq_("./Promise");assign(Transition.prototype,{abort:function(reason){this.abortReason=reason,this.isAborted=!0},redirect:function(to,params,query){this.abort(new Redirect(to,params,query))},wait:function(value){this._promise=Promise.resolve(value)},from:function(routes,components,callback){return runTransitionFromHooks(this,routes,components,callback)},to:function(routes,params,query,callback){return runTransitionToHooks(this,routes,params,query,callback)}}),module.exports=Transition},{"./Promise":20,"./Redirect":22,"./reversedArray":27,"react/lib/Object.assign":36}],24:[function(_dereq_,module){function defaultErrorHandler(error){throw error}function defaultAbortHandler(abortReason,location){if("string"==typeof location)throw new Error("Unhandled aborted transition! Reason: "+abortReason);abortReason instanceof Redirect?location.replace(this.makePath(abortReason.to,abortReason.params,abortReason.query)):location.pop()}function findMatch(pathname,routes,defaultRoute,notFoundRoute){for(var match,route,params,i=0,len=routes.length;len>i;++i){if(route=routes[i],match=findMatch(pathname,route.childRoutes,route.defaultRoute,route.notFoundRoute),null!=match)return match.routes.unshift(route),match;if(params=Path.extractParams(route.path,pathname))return createMatch(route,params)}return defaultRoute&&(params=Path.extractParams(defaultRoute.path,pathname))?createMatch(defaultRoute,params):notFoundRoute&&(params=Path.extractParams(notFoundRoute.path,pathname))?createMatch(notFoundRoute,params):match}function createMatch(route,params){return{routes:[route],params:params}}function hasMatch(routes,route,prevParams,nextParams){return routes.some(function(r){if(r!==route)return!1;for(var paramName,paramNames=route.paramNames,i=0,len=paramNames.length;len>i;++i)if(paramName=paramNames[i],nextParams[paramName]!==prevParams[paramName])return!1;return!0})}function createRouter(options){options=options||{},"function"==typeof options?options={routes:options}:Array.isArray(options)&&(options={routes:options});var routes=[],namedRoutes={},components=[],location=options.location||DEFAULT_LOCATION,scrollBehavior=options.scrollBehavior||DEFAULT_SCROLL_BEHAVIOR,onError=options.onError||defaultErrorHandler,onAbort=options.onAbort||defaultAbortHandler,state={};location!==HistoryLocation||supportsHistory()||(location=RefreshLocation);var router=React.createClass({displayName:"Router",mixins:[NavigationContext,StateContext,Scrolling],statics:{defaultRoute:null,notFoundRoute:null,addRoutes:function(children){routes.push.apply(routes,createRoutesFromChildren(children,this,namedRoutes))},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var route=namedRoutes[to];invariant(route,'Unable to find <Route name="%s">',to),path=route.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return location===HashLocation?"#"+path:path},transitionTo:function(to,params,query){invariant("string"!=typeof location,"You cannot use transitionTo with a static location"),location.push(this.makePath(to,params,query))},replaceWith:function(to,params,query){invariant("string"!=typeof location,"You cannot use replaceWith with a static location"),location.replace(this.makePath(to,params,query))},goBack:function(){invariant("string"!=typeof location,"You cannot use goBack with a static location"),location.pop()},match:function(path){return findMatch(Path.withoutQuery(path),routes,this.defaultRoute,this.notFoundRoute)||null},dispatch:function(path,action,callback){if(state.path!==path){var match=this.match(path);warning(null!=match,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your routes',path,path),null==match&&(match={});var fromRoutes,toRoutes,prevRoutes=state.routes||[],prevParams=state.params||{},nextRoutes=match.routes||[],nextParams=match.params||{},nextQuery=Path.extractQuery(path)||{};prevRoutes.length?(fromRoutes=prevRoutes.filter(function(route){return!hasMatch(nextRoutes,route,prevParams,nextParams)}),toRoutes=nextRoutes.filter(function(route){return!hasMatch(prevRoutes,route,prevParams,nextParams)})):(fromRoutes=[],toRoutes=nextRoutes);var transition=new Transition(path,this.replaceWith.bind(this,path));transition.from(fromRoutes,components,function(error){return error||transition.isAborted?callback.call(router,error,transition):void transition.to(toRoutes,nextParams,nextQuery,function(error){return error||transition.isAborted?callback.call(router,error,transition):(state.path=path,state.action=action,state.routes=nextRoutes,state.params=nextParams,state.query=nextQuery,void callback.call(router,null,transition))})})}},run:function(callback){function dispatchHandler(error,transition){error?onError.call(router,error):transition.isAborted?onAbort.call(router,transition.abortReason,location):callback.call(router,router,state)}function changeListener(change){router.dispatch(change.path,change.type,dispatchHandler)}"string"==typeof location?(warning(!canUseDOM||!1,"You should not use a static location in a DOM environment because the router will not be kept in sync with the current URL"),router.dispatch(location,null,dispatchHandler)):(invariant(canUseDOM,"You cannot use %s in a non-DOM environment",location),location.addChangeListener&&location.addChangeListener(changeListener),router.dispatch(location.getCurrentPath(),null,dispatchHandler))}},propTypes:{children:PropTypes.falsy},getLocation:function(){return location},getScrollBehavior:function(){return scrollBehavior},getRouteAtDepth:function(depth){var routes=this.state.routes;return routes&&routes[depth]},getRouteComponents:function(){return components},getInitialState:function(){return state},componentWillReceiveProps:function(){this.setState(state)},render:function(){return this.getRouteAtDepth(0)?React.createElement(RouteHandler,this.props):null},childContextTypes:{getRouteAtDepth:React.PropTypes.func.isRequired,getRouteComponents:React.PropTypes.func.isRequired,routeHandlers:React.PropTypes.array.isRequired},getChildContext:function(){return{getRouteComponents:this.getRouteComponents,getRouteAtDepth:this.getRouteAtDepth,routeHandlers:[this]}}});return options.routes&&router.addRoutes(options.routes),router}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),RouteHandler=_dereq_("../components/RouteHandler"),HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),NavigationContext=_dereq_("../mixins/NavigationContext"),StateContext=_dereq_("../mixins/StateContext"),Scrolling=_dereq_("../mixins/Scrolling"),createRoutesFromChildren=_dereq_("./createRoutesFromChildren"),supportsHistory=_dereq_("./supportsHistory"),Transition=_dereq_("./Transition"),PropTypes=_dereq_("./PropTypes"),Redirect=_dereq_("./Redirect"),Path=_dereq_("./Path"),DEFAULT_LOCATION=canUseDOM?HashLocation:"/",DEFAULT_SCROLL_BEHAVIOR=canUseDOM?ImitateBrowserBehavior:null;module.exports=createRouter},{"../behaviors/ImitateBrowserBehavior":2,"../components/RouteHandler":8,"../locations/HashLocation":10,"../locations/HistoryLocation":11,"../mixins/NavigationContext":15,"../mixins/Scrolling":16,"../mixins/StateContext":18,"./Path":19,"./PropTypes":21,"./Redirect":22,"./Transition":23,"./createRoutesFromChildren":25,"./supportsHistory":29,"react/lib/ExecutionEnvironment":35,"react/lib/invariant":39,"react/lib/warning":40}],25:[function(_dereq_,module){function createRedirectHandler(to,_params,_query){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,_params||params,_query||query)}},render:function(){return null}})}function checkPropTypes(componentName,propTypes,props){for(var propName in propTypes)if(propTypes.hasOwnProperty(propName)){var error=propTypes[propName](props,propName,componentName);error instanceof Error&&warning(!1,error.message)}}function createRoute(element,parentRoute,namedRoutes){var type=element.type,props=element.props,componentName=type&&type.displayName||"UnknownComponent";invariant(-1!==CONFIG_ELEMENT_TYPES.indexOf(type),'Unrecognized route configuration element "<%s>"',componentName),type.propTypes&&checkPropTypes(componentName,type.propTypes,props);var route={name:props.name};type===Redirect.type?(route.handler=createRedirectHandler(props.to,props.params,props.query),props.path=props.path||props.from):route.handler=props.handler;var parentPath=parentRoute&&parentRoute.path||"/";if((props.path||props.name)&&type!==DefaultRoute.type&&type!==NotFoundRoute.type){var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),route.path=Path.normalize(path)}else route.path=parentPath,type===NotFoundRoute.type&&(route.path+="*");return route.paramNames=Path.extractParamNames(route.path),parentRoute&&Array.isArray(parentRoute.paramNames)&&parentRoute.paramNames.forEach(function(paramName){invariant(-1!==route.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',route.path,paramName,parentRoute.path)}),props.name&&(invariant(null==namedRoutes[props.name],'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route),type===NotFoundRoute.type?(invariant(parentRoute,"<NotFoundRoute> must have a parent <Route>"),invariant(null==parentRoute.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),parentRoute.notFoundRoute=route,null):type===DefaultRoute.type?(invariant(parentRoute,"<DefaultRoute> must have a parent <Route>"),invariant(null==parentRoute.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),parentRoute.defaultRoute=route,null):(route.childRoutes=createRoutesFromChildren(props.children,route,namedRoutes),route)}function createRoutesFromChildren(children,parentRoute,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=createRoute(child,parentRoute,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),DefaultRoute=_dereq_("../components/DefaultRoute"),NotFoundRoute=_dereq_("../components/NotFoundRoute"),Redirect=_dereq_("../components/Redirect"),Route=_dereq_("../components/Route"),Path=_dereq_("./Path"),CONFIG_ELEMENT_TYPES=[DefaultRoute.type,NotFoundRoute.type,Redirect.type,Route.type];module.exports=createRoutesFromChildren},{"../components/DefaultRoute":3,"../components/NotFoundRoute":5,"../components/Redirect":6,"../components/Route":7,"./Path":19,"react/lib/invariant":39,"react/lib/warning":40}],26:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM;module.exports=getWindowScrollPosition},{"react/lib/ExecutionEnvironment":35,"react/lib/invariant":39}],27:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],28:[function(_dereq_,module){function runRouter(routes,location,callback){"function"==typeof location&&(callback=location,location=null);var router=createRouter({routes:routes,location:location});return router.run(callback),router}var createRouter=_dereq_("./createRouter");module.exports=runRouter},{"./createRouter":24}],29:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],30:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":31}],31:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse"); module.exports={stringify:Stringify,parse:Parse}},{"./parse":32,"./stringify":33}],32:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":34}],33:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":34}],34:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],35:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],36:[function(_dereq_,module){function assign(target){if(null==target)throw new TypeError("Object.assign target cannot be null or undefined");for(var to=Object(target),hasOwnProperty=Object.prototype.hasOwnProperty,nextIndex=1;nextIndex<arguments.length;nextIndex++){var nextSource=arguments[nextIndex];if(null!=nextSource){var from=Object(nextSource);for(var key in from)hasOwnProperty.call(from,key)&&(to[key]=from[key])}}return to}module.exports=assign},{}],37:[function(_dereq_,module){function cx(classNames){return"object"==typeof classNames?Object.keys(classNames).filter(function(className){return classNames[className]}).join(" "):Array.prototype.join.call(arguments," ")}module.exports=cx},{}],38:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],39:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],40:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":38}],41:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":43,"./async":44,"./makePromise":45}],42:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],43:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":42}],44:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],45:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state();if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[9])(9)});
src/app/BoardView.js
smonev/15-Puzzle
import React from 'react'; import Board15 from './games/Board15'; // import AbcBoard from './games/AbcBoard'; import Cell from './Cell'; import LevelView from './Level'; import TileView from './TileView'; require('../sass/index.scss'); export default class BoardView extends React.Component { componentDidMount() { document.addEventListener('mousemove', this.mousemove.bind(this)); document.addEventListener('touchmove', this.mousemove.bind(this), false); } componentWillUnmount() { document.removeEventListener('mousemove', this.mousemove.bind(this)); document.removeEventListener('touchmove', this.mousemove.bind(this)); } onBoardTouchOrMouseMove(event, domElement) { if (this.state.resetTile) { this.setState({ resetTile: null, }); } this.state.board.checkForCollision(domElement.props.tile, this.onHoverWhileMoving); } onBoardTouchOrMoveStart() { this.setState({ hasMoved: false, hasWon: false, }); } onBoardTouchOrMoveEnd(event, domElement, fromTile) { this.state.board.checkForCollision(domElement.props.tile, function(toTile) { let newTiles = this.state.board.move(fromTile, toTile); if (typeof newTiles !== 'undefined') { this.state.board.tiles = newTiles; this.setState({ board: this.state.board, hasMoved: true, }); this.checkForWin(); } else { this.setState({ resetTile: fromTile, }); } }.bind(this)); let hovered = document.querySelector('.hovered'); if (hovered !== null) { hovered.classList.remove('hovered'); } } onHoverWhileMoving(tile) { if (typeof tile !== 'undefined') { let newHovered = document.querySelector('.position_' + tile.row + '_' + tile.column); let hovered = document.querySelector('.hovered'); if ((hovered !== null) && (newHovered !== null)) { if (hovered !== newHovered) { hovered.classList.remove('hovered'); newHovered.classList.add('hovered'); } } else if (hovered !== null) { hovered.classList.remove('hovered'); } else if (newHovered !== null) { newHovered.classList.add('hovered'); } } } onLevelClick() { this.setState({ showLevel: !this.state.showLevel, }); } render() { const that = this; let result; const cells = this.state.board.cells.map(function(row, i) { if (row.length) { result = ( <div key={i}> {row.map( function(item, j) { return <Cell width={that.state.board.CELL_WIDTH} key={j} />; } )} </div> ); } else { result = <Cell width={that.state.board.CELL_WIDTH} key={i} />; } return result; }); const tiles = this.state.board.tiles.filter(function(tile) { return tile.value !== 0; }).map(function(tile) { let resetTile; if (tile === that.state.resetTile) { resetTile = tile; } return ( <TileView tile={tile} key={tile.id} resetTile={resetTile} dimension={that.state.board.dimension} mousemoveEvent={that.state.mousemoveEvent} width={that.state.board.CELL_WIDTH} hasWon={that.state.hasWon} hasMoved={that.state.hasMoved} tileBackgroundColor={that.state.tileBackgroundColor} tileRadius={that.state.tileRadius} onBoardTouchOrMouseMove={that.onBoardTouchOrMouseMove.bind(that)} onBoardTouchOrMoveStart={that.onBoardTouchOrMoveStart.bind(that)} onBoardTouchOrMoveEnd={that.onBoardTouchOrMoveEnd.bind(that)} /> ); }); return ( <div className="board" tabIndex="1"> <LevelView level={that.state.board.level} tileWidth={that.state.board.CELL_WIDTH} hasWon={that.state.hasWon} showLevel={that.state.showLevel} onLevelClick={that.onLevelClick.bind(that)} /> {cells} {tiles} </div> ); } checkForWin() { if (this.state.board.hasWon()) { this.state.board.tiles = this.state.board.initializeLevel(this.state.board.level); this.state.board.level = this.state.board.level + 1; this.setState({ board: this.state.board, hasWon: true, tileBackgroundColor: this.chooseTileBackgroundColor(), tileRadius: this.chooseTileRadius(), showLevel: true, }); } } mousemove(event) { event.stopPropagation(); event.preventDefault(); this.setState({ mousemoveEvent: event, // Whole event? hmm }); } chooseTileBackgroundColor() { const colors = ['8bc34a', 'ffeb3b', 'ffc107', 'ff5722', 'e91e63', '259b24', 'cddc39', 'ff9800', 'e51c23', '9c27b0', '3f51b5', '03a9f4', '00bcd4', '607d8b', '673ab7', '5677fc', '009688', '795548']; return '#' + colors[Math.floor(Math.random() * colors.length)]; } chooseTileRadius() { let maximum = 50; let minimum = 0; let randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; return randomnumber + '%'; } constructor() { super(); this.state = { board: new Board15(), // board: new AbcBoard(), showLevel: false, mousemoveEvent: null, hasWon: false, hasMoved: false, tileBackgroundColor: this.chooseTileBackgroundColor(), tileRadius: this.chooseTileRadius(), }; } }
src/common/movie-list-horizontal.js
rldona/react-native-tab-view-seed
import React, { Component } from 'react'; import { View, Text, Image, TouchableOpacity, ListView, StyleSheet, Dimensions, Vibration, ToastAndroid, InteractionManager } from 'react-native'; import * as firebase from 'firebase'; import * as themoviedb from '../services/movies-service.js'; import * as colors from './colors'; import Icon from 'react-native-vector-icons/MaterialIcons'; import Loading from '../common/loading'; const { width, height } = Dimensions.get('window'); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); export default class MoviesListHorizontal extends Component { constructor(props) { super(props); if (typeof this.props.list !== 'undefined') { movies = this.props.list; } this.state = { dataMovies: typeof this.props.list === 'undefined' ? [] : this.props.list, }; } componentDidMount() { // InteractionManager.runAfterInteractions(() => { this.loadMovies(); // }); } loadMovies() { if (this.props.collection === 'similar') { themoviedb.getSimilar(this.props.type, themoviedb.getCurrentMovie().id).then((data) => { movies = []; movies = data; page = 2; this.setState({ 'dataMovies': ds.cloneWithRows(data) }); }); } } _onSelectMovie(movie) { // themoviedb.getMovie('movie', movie.id).then((data) => { // data.runtime = data.runtime === 0 ? 90 : data.runtime; // themoviedb.setCurrentMovie(data); // themoviedb.getNavigator().push({index: 2, route: 'movie-detail'}); // }); let user = firebase.auth().currentUser; if (user) { if (themoviedb.findFavorite(movie.id) === -1) { firebase.database().ref('users/' + user.uid + '/favorites/' + movie.id + '/').set({ saved: false, viewed: false, favorite: false }); } themoviedb.setFavorite(movie.id, 'movie'); } themoviedb.setCurrentMovie(movie); themoviedb.setHistorialList(movie); this.props.actions.historial.add(movie); if (movie.first_air_date) { themoviedb.getNavigator().push({index: 2.1, route: 'movie-detail-tv'}); } else { themoviedb.getNavigator().push({index: 2, route: 'movie-detail'}); } } renderMovie(movie) { return( <TouchableOpacity onPress={this._onSelectMovie.bind(this, movie)} onLongPress={() => {ToastAndroid.show(movie.title, ToastAndroid.SHORT); Vibration.vibrate([0, 20])}} activeOpacity={0.9}> <View style={{paddingVertical: 10}}> <Image resizeMode={'cover'} style={{width: 120, height: 170, borderRadius: 3, marginHorizontal: 10, backfaceVisibility: 'hidden'}} source={{uri: 'http://image.tmdb.org/t/p/w154' + movie.poster_path}} /> </View> </TouchableOpacity> ) } renderScrollMovieList() { if (this.state.dataMovies.length === 0 && typeof this.props.showLoading === 'undefined') { return null; } return ( <View> <View style={{flexDirection: 'row', justifyContent: 'space-between', paddingTop: 15}}> <Text style={styles.title}> {this.props.title} </Text> <TouchableOpacity activeOpacity={0.9} onPress={() => { themoviedb.setCurrentTitle(this.props.title); themoviedb.setCurrentType(this.props.type); themoviedb.setCurrentCollection(this.props.collection); themoviedb.getNavigator().push({index: 4, route: 'top-list'}); }}> <Text style={styles.viewAll}>VER TODAS</Text> </TouchableOpacity> </View> <ListView style={{ marginBottom: 0}} dataSource={this.state.dataMovies} pagingEnabled={false} renderRow={(rowData) => this.renderMovie(rowData)} horizontal={true} showsHorizontalScrollIndicator={false} removeClippedSubviews={false} enableEmptySections={true} /> </View> ) } render() { return ( <View renderToHardwareTextureAndroid={true}> {this.renderScrollMovieList()} </View> ); } } var styles = StyleSheet.create({ title: { color: '#FFF', fontWeight: '400', paddingTop: 5, paddingLeft: 15, fontSize: 17, marginBottom: 15, }, viewAll: { color: colors.getList().app, fontSize: 11, marginTop: 3, marginRight: 10, paddingTop: 5, paddingBottom: 5, minWidth: 80, borderRadius: 3, borderWidth: 1, borderColor: colors.getList().app, textAlign: 'center' }, movie: { paddingTop: 10, paddingBottom: 10, paddingHorizontal: 5, borderTopWidth: 2, borderBottomWidth: 2, } });
client2/src/components/whiteboard/colorbox.js
gdomorski/CodeOut
import React, { Component } from 'react'; import InputColor from 'react-input-color' export default (props) => { const texty = { 'color': 'white', 'marginRight': '5px', 'width': '150px' }; return ( <div className="app animated slideInLeft"> <span style={texty}>Tool: </span> <input type="color" value={props.brushColor} defaultValue="#345678" onChange={props.changeParentColor} /> </div> ) }
ajax/libs/reactive-coffee/0.0.0/reactive-coffee.js
zauguin/cdnjs
(function() { var DepArray, DepCell, DepMgr, Depmap, Ev, MappedDepArray, ObsArray, ObsCell, ObsMap, RawHtml, Recorder, SrcArray, SrcCell, SrcMap, bind, depMgr, lagBind, mktag, mkuid, nextUid, popKey, recorder, rx, rxt, tag, tags, _ref, _ref1, _ref2, _ref3, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, _this = this; if (typeof exports === 'undefined') { this.rx = rx = {}; } else { rx = exports; } nextUid = 0; mkuid = function() { return nextUid += 1; }; popKey = function(x, k) { var v; if (!k in x) { throw 'object has no key ' + k; } v = x[k]; delete x[k]; return v; }; Recorder = rx.Recorder = (function() { function Recorder() { this.stack = []; } Recorder.prototype.start = function(dep) { return this.stack.push(dep); }; Recorder.prototype.stop = function() { return this.stack.pop(); }; Recorder.prototype.sub = function(sub) { var handle, topCell; if (this.stack.length > 0) { topCell = _(this.stack).last(); handle = sub(topCell); return topCell.addSub(handle); } }; Recorder.prototype.warnMutate = function() { if (this.stack.length > 0) { return console.warn('Mutation to observable detected during a bind context'); } }; return Recorder; })(); recorder = new Recorder(); rx.bind = bind = function(f) { var dep; dep = rx.depCell(f); dep.refresh(); return dep; }; rx.lagBind = lagBind = function(init, f) { var dep; dep = rx.lagDepCell(f, init); dep.refresh(); return dep; }; DepMgr = rx.DepMgr = (function() { function DepMgr() { this.uid2src = {}; } DepMgr.prototype.sub = function(uid, src) { return this.uid2src[uid] = src; }; DepMgr.prototype.unsub = function(uid) { this.uid2src[uid].unsub(uid); return popKey(this.uid2src, uid); }; return DepMgr; })(); depMgr = new DepMgr(); Ev = rx.Ev = (function() { function Ev(inits) { this.inits = inits; this.subs = []; } Ev.prototype.sub = function(listener) { var init, uid, _i, _len, _ref; uid = mkuid(); if (this.inits != null) { _ref = this.inits(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { init = _ref[_i]; listener(init); } } this.subs[uid] = listener; depMgr.sub(uid, this); return uid; }; Ev.prototype.pub = function(data) { var listener, uid, _ref, _results; _ref = this.subs; _results = []; for (uid in _ref) { listener = _ref[uid]; _results.push(listener(data)); } return _results; }; Ev.prototype.unsub = function(uid) { return popKey(this.subs, uid); }; return Ev; })(); ObsCell = rx.ObsCell = (function() { function ObsCell(x) { var _ref, _this = this; this.x = x; this.x = (_ref = this.x) != null ? _ref : null; this.onSet = new Ev(function() { return [[null, _this.x]]; }); } ObsCell.prototype.get = function() { var _this = this; recorder.sub(function(target) { return _this.onSet.sub(function() { return target.refresh(); }); }); return this.x; }; return ObsCell; })(); SrcCell = rx.SrcCell = (function(_super) { __extends(SrcCell, _super); function SrcCell() { _ref = SrcCell.__super__.constructor.apply(this, arguments); return _ref; } SrcCell.prototype.set = function(x) { var old; recorder.warnMutate(); old = this.x; this.x = x; this.onSet.pub([old, x]); return old; }; return SrcCell; })(ObsCell); DepCell = rx.DepCell = (function(_super) { __extends(DepCell, _super); function DepCell(body, init, lag) { this.body = body; DepCell.__super__.constructor.call(this, init != null ? init : null); this.subs = []; this.refreshing = false; this.lag = lag != null ? lag : false; this.timeout = null; } DepCell.prototype.refresh = function() { var realRefresh, _this = this; realRefresh = function() { var old, subUid, _i, _len, _ref1; if (!_this.refreshing) { old = _this.x; _ref1 = _this.subs; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { subUid = _ref1[_i]; depMgr.unsub(subUid); } _this.subs = []; recorder.start(_this); _this.refreshing = true; try { _this.x = _this.body(); } finally { _this.refreshing = false; recorder.stop(); } return _this.onSet.pub([old, _this.x]); } }; if (!this.refreshing) { if (this.lag) { if (this.timeout != null) { clearTimeout(this.timeout); } console.log('setting timeout'); return this.timeout = setTimeout(realRefresh, 500); } else { return realRefresh(); } } }; DepCell.prototype.addSub = function(subUid) { return this.subs.push(subUid); }; return DepCell; })(ObsCell); ObsArray = rx.ObsArray = (function() { function ObsArray(xs) { var _ref1, _this = this; this.xs = xs; this.xs = (_ref1 = this.xs) != null ? _ref1 : []; this.onChange = new Ev(function() { return [[0, [], _this.xs]]; }); } ObsArray.prototype.all = function() { var _this = this; recorder.sub(function(target) { return _this.onChange.sub(function() { return target.refresh(); }); }); return this.xs; }; ObsArray.prototype.at = function(i) { var _this = this; recorder.sub(function(target) { return _this.onChange.sub(function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; if (index === i) { return target.refresh(); } }); }); return this.xs[i]; }; ObsArray.prototype.length = function() { var _this = this; recorder.sub(function(target) { return _this.onChange.sub(function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; if (removed.length !== added.length) { return target.refresh(); } }); }); return this.xs.length; }; ObsArray.prototype.map = function(f) { var ys; ys = new MappedDepArray(); this.onChange.sub(function(_arg) { var added, index, removed; index = _arg[0], removed = _arg[1], added = _arg[2]; return ys.realSplice(index, removed.length, added.map(f)); }); return ys; }; ObsArray.prototype.realSplice = function(index, count, additions) { var removed; removed = this.xs.splice.apply(this.xs, [index, count].concat(additions)); return this.onChange.pub([index, removed, additions]); }; return ObsArray; })(); SrcArray = rx.SrcArray = (function(_super) { __extends(SrcArray, _super); function SrcArray() { _ref1 = SrcArray.__super__.constructor.apply(this, arguments); return _ref1; } SrcArray.prototype.spliceArray = function(index, count, additions) { recorder.warnMutate(); return this.realSplice(index, count, additions); }; SrcArray.prototype.splice = function() { var additions, count, index; index = arguments[0], count = arguments[1], additions = 3 <= arguments.length ? __slice.call(arguments, 2) : []; return this.spliceArray(index, count, additions); }; SrcArray.prototype.insert = function(x, index) { return this.splice(index, 0, x); }; SrcArray.prototype.remove = function(x) { return this.removeAt(_(this.all()).indexOf(x)); }; SrcArray.prototype.removeAt = function(index) { return this.splice(index, 1); }; SrcArray.prototype.push = function(x) { return this.splice(this.length(), 0, x); }; SrcArray.prototype.put = function(i, x) { return this.splice(i, 1, x); }; SrcArray.prototype.replace = function(xs) { return this.spliceArray(0, this.length(), xs); }; return SrcArray; })(ObsArray); MappedDepArray = rx.MappedDepArray = (function(_super) { __extends(MappedDepArray, _super); function MappedDepArray() { _ref2 = MappedDepArray.__super__.constructor.apply(this, arguments); return _ref2; } return MappedDepArray; })(ObsArray); DepArray = rx.DepArray = (function(_super) { __extends(DepArray, _super); function DepArray(f) { this.f = f; DepArray.__super__.constructor.call(this); new DepCell(this.f).onSet.sub(function(_arg) { var additions, count, index, old, val, _i, _ref3, _ref4, _results; old = _arg[0], val = _arg[1]; _ref4 = firstWhere((function() { _results = []; for (var _i = 0, _ref3 = Math.min(old.length, val.length); 0 <= _ref3 ? _i <= _ref3 : _i >= _ref3; 0 <= _ref3 ? _i++ : _i--){ _results.push(_i); } return _results; }).apply(this), function(i) { return old[i] !== val[i]; }), index = _ref4[0], index = _ref4[1]; if (index > -1) { count = old.length - index; additions = val.slice(index); return this.realSplice(index, count, additions); } }); } return DepArray; })(ObsArray); ObsMap = rx.ObsMap = (function() { function ObsMap(x) { var _this = this; this.x = x != null ? x : {}; this.onAdd = new Ev(function() { var k, v, _results; _results = []; for (k in x) { v = x[k]; _results.push([k, v]); } return _results; }); this.onRemove = new Ev(); this.onChange = new Ev(); } ObsMap.prototype.get = function(key) { var _this = this; recorder.sub(function(target) { return _this.onChange.sub(function(_arg) { var old, subkey, val; subkey = _arg[0], old = _arg[1], val = _arg[2]; if (key === subkey) { return target.refresh(); } }); }); return this.x[key]; }; ObsMap.prototype.all = function() { var _this = this; recorder.sub(function(target) { return _this.onChange.sub(function() { return target.refresh(); }); }); return _.clone(this.x); }; ObsMap.prototype.realPut = function(key, val) { var old; if (__indexOf.call(this.x, key) >= 0) { old = this.x[key]; this.x[key] = val; this.onChange.pub([key, old, val]); return old; } else { this.x[key] = val; this.onAdd.pub([key, val]); return void 0; } }; ObsMap.prototype.realRemove = function(key) { var val; val = popKey(this.x, key); this.onRemove.pub([key, val]); return val; }; return ObsMap; })(); SrcMap = rx.SrcMap = (function(_super) { __extends(SrcMap, _super); function SrcMap() { _ref3 = SrcMap.__super__.constructor.apply(this, arguments); return _ref3; } SrcMap.prototype.put = function(key, val) { recorder.warnMutate(); return this.realPut(key, val); }; SrcMap.prototype.remove = function(key) { recorder.warnMutate(); return this.realRemove(key); }; return SrcMap; })(ObsMap); Depmap = rx.DepMap = (function(_super) { __extends(DepMap, _super); function DepMap(f) { this.f = f; DepMap.__super__.constructor.call(this); new DepCell(this.f).onSet.sub(function(_arg) { var k, old, v, val, _results; old = _arg[0], val = _arg[1]; for (k in old) { v = old[k]; if (!k in val) { this.realRemove(k); } } _results = []; for (k in val) { v = val[k]; if (this.x[k] !== v) { _results.push(this.realPut(k, v)); } else { _results.push(void 0); } } return _results; }); } return DepMap; })(ObsMap); _.extend(rx, { cell: function(x) { return new SrcCell(x); }, array: function(xs) { return new SrcArray(xs); }, map: function(x) { return new SrcMap(x); }, depCell: function(f) { return new DepCell(f); }, lagDepCell: function(f, init) { return new DepCell(f, init, true); }, depMap: function(f) { return new DepMap(f); }, depArray: function(f) { return new DepArray(f); } }); $.fn.rx = function(prop) { var checked, focused, map, val; map = $(this).data('rx-map'); if (map == null) { map = $(this).data('rx-map', mkMap()); } if (__indexOf.call(map, prop) >= 0) { return map[prop]; } return map[prop] = (function() { switch (prop) { case 'focused': focused = rx.cell($(this).is(':focus')); $(this).focus(function() { return focused.set(true); }); $(this).blur(function() { return focused.set(false); }); return bind(function() { return focused.get(); }); case 'val': val = rx.cell($(this).val()); $(this).change(function() { return val.set(val); }); return bind(function() { return val.get(); }); case 'checked': checked = rx.cell($(this).is(':checked')); $(this).change(function() { return checked.set($(this).is(':checked')); }); return bind(function() { return checked.get(); }); default: throw 'Unknown reactive property type'; } }).call(this); }; if (typeof exports === 'undefined') { this.rxt = rxt = {}; } else { rxt = exports; } RawHtml = rxt.RawHtml = (function() { function RawHtml(html) { this.html = html; } return RawHtml; })(); rxt.mktag = mktag = function(tag) { return function(attrs, contents) { var elt, name, updateContents, value, _ref4, _ref5; elt = $("<" + tag + "/>"); _ref4 = _.omit(attrs, 'init'); for (name in _ref4) { value = _ref4[name]; if (value instanceof ObsCell) { (function(name) { return value.onSet.sub(function(_arg) { var old, val; old = _arg[0], val = _arg[1]; return elt.attr(name, val); }); })(name); } else { elt.attr(name, value); } } if (contents != null) { updateContents = function(contents) { var child, _i, _len, _results; elt.html(''); if (_.isArray(contents)) { _results = []; for (_i = 0, _len = contents.length; _i < _len; _i++) { child = contents[_i]; if (_.isString(child)) { child = $('<span/>').text(child); } else if (child instanceof RawHtml) { child = $('<span/>').html(child.html); } _results.push(elt.append(child)); } return _results; } else { throw 'Unknown type for contents: ' + contents.constructor.name; } }; if (contents instanceof ObsArray) { contents.onChange.sub(function(_arg) { var added, child, index, removed, toAdd; index = _arg[0], removed = _arg[1], added = _arg[2]; elt.children().slice(index, index + removed.length).remove(); toAdd = $((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = added.length; _i < _len; _i++) { child = added[_i]; _results.push(child.get(0)); } return _results; })()); if (index === elt.children().length) { return elt.append(toAdd); } else { return elt.children().slice(index, index + 1).before(toAdd); } }); } else if (contents instanceof ObsCell) { contents.onSet.sub(function(_arg) { var old, val; old = _arg[0], val = _arg[1]; return updateContents(val); }); } else if (_.isArray(contents)) { updateContents(contents); } else { throw 'Unknown type for contents: ' + contents.constructor.name; } } if ((_ref5 = attrs.init) != null) { _ref5.call(elt); } return elt; }; }; tags = ['html', 'head', 'title', 'base', 'link', 'meta', 'style', 'script', 'noscript', 'body', 'body', 'section', 'nav', 'article', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h1', 'h6', 'header', 'footer', 'address', 'main', 'main', 'p', 'hr', 'pre', 'blockquote', 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'dd', 'figure', 'figcaption', 'div', 'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data', 'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr', 'ins', 'del', 'img', 'iframe', 'embed', 'object', 'param', 'object', 'video', 'audio', 'source', 'video', 'audio', 'track', 'video', 'audio', 'canvas', 'map', 'area', 'area', 'map', 'svg', 'math', 'table', 'caption', 'colgroup', 'col', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'form', 'fieldset', 'legend', 'fieldset', 'label', 'input', 'button', 'select', 'datalist', 'optgroup', 'option', 'select', 'datalist', 'textarea', 'keygen', 'output', 'progress', 'meter', 'details', 'summary', 'details', 'menuitem', 'menu']; rxt.tags = _.object((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = tags.length; _i < _len; _i++) { tag = tags[_i]; _results.push([tag, rxt.mktag(tag)]); } return _results; })()); rxt.rawHtml = function(html) { return new RawHtml(html); }; rxt.importTags = function(x) { return _(x != null ? x : _this).extend(rxt.tags); }; }).call(this);
src/svg-icons/action/gif.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGif = (props) => ( <SvgIcon {...props}> <path d="M11.5 9H13v6h-1.5zM9 9H6c-.6 0-1 .5-1 1v4c0 .5.4 1 1 1h3c.6 0 1-.5 1-1v-2H8.5v1.5h-2v-3H10V10c0-.5-.4-1-1-1zm10 1.5V9h-4.5v6H16v-2h2v-1.5h-2v-1z"/> </SvgIcon> ); ActionGif = pure(ActionGif); ActionGif.displayName = 'ActionGif'; ActionGif.muiName = 'SvgIcon'; export default ActionGif;
js/src/ui/Warning/warning.js
jesuscript/parity
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import { nodeOrStringProptype } from '~/util/proptypes'; import styles from './warning.css'; export default class Warning extends Component { static propTypes = { warning: nodeOrStringProptype() }; render () { const { warning } = this.props; if (!warning) { return null; } return ( <div className={ styles.warning }> { warning } </div> ); } }
ajax/libs/core-js/0.1.4/library.js
quba/cdnjs
/** * Core.js 0.1.4 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2014 Denis Pushkarev */ !function(returnThis, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ var global = returnThis() // Shortcuts for [[Class]] & property names , OBJECT = 'Object' , FUNCTION = 'Function' , ARRAY = 'Array' , STRING = 'String' , NUMBER = 'Number' , REGEXP = 'RegExp' , DATE = 'Date' , MAP = 'Map' , SET = 'Set' , WEAKMAP = 'WeakMap' , WEAKSET = 'WeakSet' , SYMBOL = 'Symbol' , PROMISE = 'Promise' , MATH = 'Math' , ARGUMENTS = 'Arguments' , PROTOTYPE = 'prototype' , CONSTRUCTOR = 'constructor' , TO_STRING = 'toString' , TO_LOCALE = 'toLocaleString' , HAS_OWN = 'hasOwnProperty' , FOR_EACH = 'forEach' , CONTAINS = 'contains' , INCLUDES = 'includes' , PROCESS = 'process' , CREATE_ELEMENT = 'createElement' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , setTimeout = global.setTimeout , clearTimeout = global.clearTimeout , setImmediate = global.setImmediate , clearImmediate = global.clearImmediate , process = global[PROCESS] , nextTick = process && process.nextTick , document = global.document , navigator = global.navigator , define = global.define , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , core = {} , path = framework ? global : core , DOT = '.' , SHARP = '#'; // http://jsperf.com/core-js-isobject function isObject(it){ return it != null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var toString = ObjectProto[TO_STRING]; var buildIn = { Undefined: 1, Null: 1, Array: 1, String: 1, Arguments: 1, Function: 1, Error: 1, Boolean: 1, Number: 1, Date: 1, RegExp: 1 } , TO_STRING_TAG = TO_STRING + 'Tag'; function setToStringTag(it, tag, stat){ if(it)has(it = stat ? it : it[PROTOTYPE], SYMBOL_TAG) || hidden(it, SYMBOL_TAG, tag); } function cof(it){ return it == undefined ? it === undefined ? 'Undefined' : 'Null' : toString.call(it).slice(8, -1); } function classof(it){ var klass = cof(it), tag; return klass == OBJECT && (tag = it[SYMBOL_TAG]) ? has(buildIn, tag) ? '~' + tag : tag : klass; } // Function var apply = FunctionProto.apply , call = FunctionProto.call; // Placeholder core._ = path._ = framework ? path._ || {} : {}; // Partial apply function part(/* ...args */){ var length = arguments.length , args = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((args[i] = arguments[i++]) === _)holder = true; return partial(this, args, length, holder, _, false); } // Internal partial application & context binding function partial(fn, argsPart, lengthPart, holder, _, bind, context){ assertFunction(fn); return function(/* ...args */){ var that = bind ? context : this , length = arguments.length , i = 0, j = 0, args; if(!holder && !length)return invoke(fn, argsPart, that); args = argsPart.slice(); if(holder)for(;lengthPart > i; i++)if(args[i] === _)args[i] = arguments[j++]; while(length > j)args.push(arguments[j++]); return invoke(fn, args, that); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && 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); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } // Object: var create = Object.create , getPrototypeOf = Object.getPrototypeOf , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , getOwnDescriptor = Object.getOwnPropertyDescriptor , getKeys = Object.keys , getNames = Object.getOwnPropertyNames , getSymbols = Object.getOwnPropertySymbols , ownKeys = function(it){ return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it); } , has = ctx(call, ObjectProto[HAS_OWN], 2) // Dummy, fix for not array-like ES3 string in es5 module , ES5Object = Object , Dict; // 19.1.2.1 Object.assign(target, source, ...) var assign = Object.assign || function(target, source){ var T = Object(target) , l = arguments.length , i = 1; while(l > i){ var S = ES5Object(arguments[i++]) , keys = getKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } function createObjectToArray(isEntries){ return function(object){ var O = ES5Object(object) , keys = getKeys(object) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; } } function keyOf(object, el){ var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = Object(this) , self = ES5Object(O) , length = toLength(self.length) , index = 0 , result = isMap ? Array(length) : isFilter ? [] : undefined , val, res; for(;length > index; index++)if(noholes || index in self){ val = self[index]; res = f(val, index, O); if(type){ if(isMap)result[index] = res; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el, fromIndex /* = 0 */){ var O = ES5Object(this) , length = toLength(O.length) , index = max(getPositiveIndex(O, fromIndex), 0); if(isContains && el != el){ for(;length > index; index++)if(sameNaN(O[index]))return isContains || index; } else for(;length > index; index++)if(isContains || index in O){ if(O[index] === el)return isContains || index; } return !isContains && -1; } } // Simple reduce to object function turn(mapfn, target /* = [] */){ assertFunction(mapfn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; for(;length > index; index++){ if(mapfn(memo, O[index], index, this) === false)break; } return memo; } function generic(A, B){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , pow = Math.pow , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 7.2.3 SameValue(x, y) function same(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function getPositiveIndex(O, index){ var index = toInteger(index); if(index < 0)index += toLength(O.length); return index; } function createReplacer(regExp, replace, isStatic){ var replacer = isObject(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function assertFunction(it){ assert(isFunction(it), it, ' is not a function!'); return it; } function assertObject(it){ assert(isObject(it), it, ' is not an object!'); return it; } function assertInstance(it, Constructor, name){ assert(it instanceof Constructor, name, ": use the 'new' operator!"); } function deprecated(fn, name, alter){ var shown, msg = name + ' is deprecated and will be removed in the future!'; if(alter)msg += ' Use ' + alter + DOT; return function(){ if(!shown && global.console && console.warn){ shown = true; console.warn(msg); } return fn.apply(this, arguments); } } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){try{return defineProperty({}, 0, ObjectProto)}catch(e){}}() , sid = 0 , hidden = createDefiner(1) , symbol = Symbol || uid , set = Symbol ? simpleSet : hidden; // Iterators var ITERATOR = 'iterator' , SYMBOL_ITERATOR = Symbol && ITERATOR in Symbol ? Symbol[ITERATOR] : uid(SYMBOL + DOT + ITERATOR) , SYMBOL_TAG = Symbol && TO_STRING_TAG in Symbol ? Symbol[TO_STRING_TAG] : uid(SYMBOL + DOT + TO_STRING_TAG) , FF_ITERATOR = '@@' + ITERATOR , SUPPORT_FF_ITER = FF_ITERATOR in ArrayProto , ITER = symbol('iter') , SHIM = symbol('shim') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} , COLLECTION_KEYS; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); // 22.1.5.2.3 %ArrayIteratorPrototype%[@@toStringTag] // 23.1.5.2.3 %MapIteratorPrototype%[@@toStringTag] // 23.2.5.2.3 %SetIteratorPrototype%[@@toStringTag] setToStringTag(Constructor, NAME + ' Iterator'); } function defineIterator(Constructor, NAME, value){ var proto = Constructor[PROTOTYPE] , HAS_FF_ITER = has(proto, FF_ITERATOR); var iter = has(proto, SYMBOL_ITERATOR) ? proto[SYMBOL_ITERATOR] : HAS_FF_ITER ? proto[FF_ITERATOR] : value; if(framework){ // Define iterator setIterator(proto, iter); // FF fix if(HAS_FF_ITER)setIterator(getPrototypeOf(iter.call(new Constructor)), returnThis); } // Plug for library Iterators[NAME] = iter; // FF & v8 fix Iterators[NAME + ' Iterator'] = returnThis; } function iterResult(done, value){ return {value: value, done: !!done}; } function isIterable(it){ var O = Object(it); return SYMBOL_ITERATOR in O || has(Iterators, classof(O)); } function getIterator(it){ return assertObject((it[SYMBOL_ITERATOR] || Iterators[classof(it)]).call(it)); } function stepCall(fn, value, entries){ return entries ? invoke(fn, value) : fn(value); } function forOf(iterable, entries, fn, that){ var iterator = getIterator(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false)return; } // DOM var html = document && document.documentElement; // core var NODE = cof(process) == PROCESS , old = global.core // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // export if(exports[key] != out)exports[key] = exp; // extend global framework && target && !own && (isGlobal || delete target[key]) && hidden(target, key, out); } } // CommonJS export if(NODE)module.exports = core; // RequireJS export if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object if(!NODE || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = ES5Object(object) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ if(has(assertObject(O), $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim result[CONSTRUCTOR][PROTOTYPE] === O || (result[$PROTO] = O); } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false) }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); if(this instanceof bound){ var instance = create(fn[PROTOTYPE]) , result = invoke(fn, args, instance); return isObject(result) ? result : instance; } return invoke(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object(DOT) && DOT[0] == DOT)){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = ES5Object(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = ES5Object(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', Function(), classof, symbol(PROTOTYPE)); /****************************************************************************** * Module : global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : es6_symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description); defineProperty(ObjectProto, tag, { configurable: true, set: function(value){ hidden(this, tag, value); } }); return set(create(Symbol[PROTOTYPE]), TAG, tag); } hidden(Symbol[PROTOTYPE], TO_STRING, function(){ return this[TAG]; }); } $define(GLOBAL + WRAP, {Symbol: Symbol}); $define(STATIC, SYMBOL, { // 19.4.2.2 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.6 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.7 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.10 Symbol.toStringTag toStringTag: SYMBOL_TAG = TO_STRING_TAG in Symbol ? Symbol[TO_STRING_TAG] : Symbol(SYMBOL + DOT + TO_STRING_TAG), pure: symbol, set: set }); setToStringTag(Symbol, SYMBOL); // 26.1.11 Reflect.ownKeys (target) $define(GLOBAL, {Reflect: {ownKeys: ownKeys}}); }(symbol('tag'), {}); /****************************************************************************** * Module : es6 * ******************************************************************************/ // ECMAScript 6 shim !function(isFinite, tmp){ $define(STATIC, OBJECT, { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: same }); // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } $define(STATIC, OBJECT, { setPrototypeOf: function(O, proto){ assertObject(O); assert(proto === null || isObject(proto), proto, ": can't set as prototype!"); if(buggy)O.__proto__ = proto; else set(O, proto); return O; } }); }(); // 20.1.2.3 Number.isInteger(number) var isInteger = Number.isInteger || function(it){ return isFinite(it) && floor(it) === it; } // 20.2.2.28 Math.sign(x) , sign = Math.sign || function sign(it){ return (it = +it) == 0 || it != it ? it : it < 0 ? -1 : 1; } , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt; // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return log(x + sqrt(x * x - 1)); }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return x == 0 ? +x : log((1 + +x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32 (x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: function(x){ return x == 0 ? +x : x > -1e-6 && x < 1e-6 ? +x + x * x / 2 : exp(x) - 1; }, // 20.2.2.16 Math.fround(x) // TODO // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function(value1, value2){ var sum = 0 , length = arguments.length , value; while(length--){ value = +arguments[length]; if(value == Infinity || value == -Infinity)return Infinity; sum += value * value; } return sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function(x, y){ var UInt16 = 0xffff , xh = UInt16 & x >>> 16 , xl = UInt16 & x , yh = UInt16 & y >>> 16 , yl = UInt16 & y; return 0 | xl * yl + (xh * yl + xl * yh << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return x > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + +x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return x == 0 ? +x : (exp(x) - exp(-x)) / 2; }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ return isFinite(x) ? x == 0 ? +x : (exp(x) - exp(-x)) / (exp(x) + exp(-x)) : sign(x); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); // 21.1.2.2 String.fromCodePoint(...codePoints) // TODO // 21.1.2.4 String.raw(callSite, ...substitutions) // TODO function includes(searchString, position /* = 0 */){ return !!~String(this).indexOf(searchString, position); } $define(PROTO, STRING, { // 21.1.3.3 String.prototype.codePointAt(pos) // TODO // String.prototype.includes(searchString, position = 0) includes: includes, // Deprecated name of String#includes contains: deprecated(includes, STRING+SHARP+CONTAINS, STRING+SHARP+INCLUDES), // 21.1.3.7 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString, endPosition /* = @length */){ var length = this.length , end = toLength(min(endPosition === undefined ? length : endPosition, length)); searchString += ''; return String(this).slice(end - searchString.length, end) === searchString; }, // 21.1.3.13 String.prototype.repeat(count) repeat: function(count){ var str = '' + this , result = '' , n = toInteger(count); assert(0 <= n, "Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)result += str; return result; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString, position /* = 0 */){ var index = toLength(min(position, this.length)); searchString += ''; return String(this).slice(index, index + searchString.length) === searchString; } }); $define(STATIC, ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike, mapfn /* -> it */, that /* = undefind */){ var O = ES5Object(arrayLike) , result = new (generic(this, Array)) , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, that, 2) : undefined , index = 0 , length; if(isIterable(O))for(var iter = getIterator(O), step; !(step = iter.next()).done;){ result[index] = mapping ? f(step.value, index) : step.value; index++; } else for(length = toLength(O.length); length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } result.length = index; return result; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) // TODO // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value, start /* = 0 */, end /* = @length */){ var length = toLength(this.length) , index = max(getPositiveIndex(this, start), 0) , endPos; if(end === undefined)endPos = length; else { endPos = toInteger(end); if(endPos < 0)endPos += length; endPos = min(endPos, length); } while(endPos > index)this[index++] = value; return this; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); // 19.1.3.6 Object.prototype.toString() if(framework){ tmp[SYMBOL_TAG] = 'x'; if(cof(tmp) != 'x')hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); } }(isFinite, {}); /****************************************************************************** * Module : immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(part.call(run, id), 0); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6_promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(Function())) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) hidden(Promise[PROTOTYPE], 'then', function(onFulfilled, onRejected){ var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false } , P = react.P = new this[CONSTRUCTOR](function(resolve, reject){ react.res = assertFunction(resolve); react.rej = assertFunction(reject); }), def = this[DEF]; def.chain.push(react); def.state && notify(def); return P; }); // 25.4.5.1 Promise.prototype.catch(onRejected) hidden(Promise[PROTOTYPE], 'catch', function(onRejected){ return this.then(undefined, onRejected); }); // 25.4.4.1 Promise.all(iterable) hidden(Promise, 'all', function(iterable){ var Promise = this , values = []; return new Promise(function(resolve, reject){ forOf(iterable, false, push, values); var remaining = values.length , results = Array(remaining); if(remaining)forEach.call(values, function(promise, index){ Promise.resolve(promise).then(function(value){ results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); }); // 25.4.4.4 Promise.race(iterable) hidden(Promise, 'race', function(iterable){ var Promise = this; return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }); // 25.4.4.5 Promise.reject(r) hidden(Promise, 'reject', function(r){ return new this(function(resolve, reject){ reject(r); }); }); // 25.4.4.6 Promise.resolve(x) hidden(Promise, 'resolve', function(x){ return isObject(x) && getPrototypeOf(x) === this[PROTOTYPE] ? x : new this(function(resolve, reject){ resolve(x); }); }); }(nextTick || setImmediate, symbol('def')); setToStringTag(Promise, PROMISE); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6_collections * ******************************************************************************/ // ECMAScript 6 collections shim !function(){ var KEYS = COLLECTION_KEYS = symbol('keys') , VALUES = symbol('values') , STOREID = symbol('storeId') , WEAKDATA = symbol('weakData') , WEAKID = symbol('weakId') , SIZE = DESC ? symbol('size') : 'size' , uid = 0 , wid = 0; function getCollection(C, NAME, test, methods, commonMethods, isMap, isWeak){ var ADDER_KEY = isMap ? 'set' : 'add' , init = commonMethods.clear; function initFromIterable(that, iterable){ if(iterable != undefined)forOf(iterable, isMap, that[ADDER_KEY], that); return that; } if(!test){ // create collection constructor C = function(iterable){ assertInstance(this, C, NAME); isWeak ? hidden(this, WEAKID, wid++) : init.call(this); initFromIterable(this, iterable); } set(C, SHIM, true); assign(C[PROTOTYPE], methods, commonMethods); isWeak || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return this[SIZE]; }}); } else { var Native = C , test_key = {} , collection = new C , adder = collection[ADDER_KEY]; // wrap to init collections from iterable if(!(SYMBOL_ITERATOR in ArrayProto && C.length)){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = Native[PROTOTYPE]; } // fix .add & .set for chaining if(framework && collection[ADDER_KEY](test_key, 1) !== collection){ hidden(C[PROTOTYPE], ADDER_KEY, function(a, b){ adder.call(this, a, b); return this; }); } } setToStringTag(C, NAME); var O = {}; O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); return C; } function fastKey(it, create){ // return it with 'S' prefix if it's string or with 'P' prefix for over primitives if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // if it hasn't object id - add next if(!has(it, STOREID)){ if(create)hidden(it, STOREID, ++uid); else return ''; } // return object id with 'O' prefix return 'O' + it[STOREID]; } function collectionMethods($VALUES){ return { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function(){ hidden(this, SIZE, 0); hidden(this, KEYS, create(null)); if($VALUES == VALUES)hidden(this, VALUES, create(null)); }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var index = fastKey(key) , keys = this[KEYS] , contains = index in keys; if(contains){ delete keys[index]; if($VALUES == VALUES)delete this[VALUES][index]; this[SIZE]--; } return contains; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , values = this[$VALUES] , keys = this[KEYS] , done = {} , k, index; do { for(index in keys){ if(index in done)continue; done[index] = true; f(values[index], keys[index], this); } } while(index != undefined && index != (k = getKeys(keys))[k.length - 1]); }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return fastKey(key) in this[KEYS]; } } } // 23.1 Map Objects Map = getCollection(Map, MAP, isNative(Map) && has(Map[PROTOTYPE], FOR_EACH), { // 23.1.3.6 Map.prototype.get(key) get: function(key){ return this[VALUES][fastKey(key)]; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ var index = fastKey(key, true) , values = this[VALUES]; if(!(index in values)){ this[KEYS][index] = same(key, -0) ? 0 : key; this[SIZE]++; } values[index] = value; return this; } }, collectionMethods(VALUES), true); // 23.2 Set Objects Set = getCollection(Set, SET, isNative(Set) && has(Set[PROTOTYPE], FOR_EACH), { // 23.2.3.1 Set.prototype.add(value) add: function(value){ var index = fastKey(value, true) , values = this[KEYS]; if(!(index in values)){ values[index] = same(value, -0) ? 0 : value; this[SIZE]++; } return this; } }, collectionMethods(KEYS)); function getWeakData(it){ has(it, WEAKDATA) || hidden(it, WEAKDATA, {}); return it[WEAKDATA]; } function weakCollectionHas(key){ return isObject(key) && has(key, WEAKDATA) && has(key[WEAKDATA], this[WEAKID]); } var weakCollectionMethods = { // 23.3.3.3 WeakMap.prototype.delete(key) // 23.4.3.4 WeakSet.prototype.delete(value) 'delete': function(key){ return weakCollectionHas.call(this, key) && delete key[WEAKDATA][this[WEAKID]]; }, // 23.3.3.5 WeakMap.prototype.has(key) // 23.4.3.5 WeakSet.prototype.has(value) has: weakCollectionHas }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, isNative(WeakMap), { // 23.3.3.4 WeakMap.prototype.get(key) get: function(key){ if(isObject(key) && has(key, WEAKDATA))return key[WEAKDATA][this[WEAKID]]; }, // 23.3.3.6 WeakMap.prototype.set(key, value) set: function(key, value){ getWeakData(assertObject(key))[this[WEAKID]] = value; return this; } }, weakCollectionMethods, true, true); // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, isNative(WeakSet), { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ getWeakData(assertObject(value))[this[WEAKID]] = true; return this; } }, weakCollectionMethods, false, true); }(); /****************************************************************************** * Module : dict * ******************************************************************************/ !function(DICT){ Dict = function(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , index = iter.i++ , keys = iter.a , kind = iter.k , key, value; if(index >= keys.length)return iterResult(1); key = keys[index]; if(kind == KEY) value = key; else if(kind == VALUE)value = iter.o[key]; else value = [key, iter.o[key]]; return iterResult(0, value); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , result = isMap || type == 7 || type == 2 ? new (generic(this, Dict)) : undefined , key, val, res; while(length > i){ key = keys[i++]; val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 2: result[key] = val; break // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i){ result = mapfn(memo, O[key = keys[i++]], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } assign(Dict, { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes: includes, contains: deprecated(includes, DICT+DOT+CONTAINS, DICT+DOT+INCLUDES), // Has / get / set own property has: has, get: function(object, key){ if(has(object, key))return object[key]; }, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }); $define(STATIC, OBJECT, { // ~ ES7 : http://esdiscuss.org/topic/april-8-2014-meeting-notes#content-1 values: createObjectToArray(false), // ~ ES7 : http://esdiscuss.org/topic/april-8-2014-meeting-notes#content-1 entries: createObjectToArray(true) }); $define(GLOBAL + FORCED, {Dict: Dict}); }('Dict'); /****************************************************************************** * Module : $for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assign($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', symbol('fn')); /****************************************************************************** * Module : es6_iterators * ******************************************************************************/ // ECMAScript 6 iterators shim !function(){ var getValues = createObjectToArray(false) // Safari define byggy iterators w/o `next` , buggy = 'keys' in ArrayProto && !('next' in [].keys()); function defineStdIterators(Base, NAME, DEFAULT, Constructor, next){ function createIter(kind){ return function(){ return new Constructor(this, kind); } } createIterator(Constructor, NAME, next); $define(PROTO + FORCED * buggy, NAME, { // 22.1.3.4 Array.prototype.entries() // 23.1.3.4 Map.prototype.entries() // 23.2.3.5 Set.prototype.entries() entries: createIter(KEY+VALUE), // 22.1.3.13 Array.prototype.keys() // 23.1.3.8 Map.prototype.keys() // 23.2.3.8 Set.prototype.keys() keys: createIter(KEY), // 22.1.3.29 Array.prototype.values() // 23.1.3.11 Map.prototype.values() // 23.2.3.10 Set.prototype.values() values: createIter(VALUE) }); // 22.1.3.30 Array.prototype[@@iterator]() // 23.1.3.12 Map.prototype[@@iterator]() // 23.2.3.11 Set.prototype[@@iterator]() Base && defineIterator(Base, NAME, createIter(DEFAULT)); } // 22.1.5.1 CreateArrayIterator Abstract Operation defineStdIterators(Array, ARRAY, VALUE, function(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , iterated = iter.o , index = iter.i++ , kind = iter.k , value; if(index >= iterated.length)return iterResult(1); if(kind == KEY) value = index; else if(kind == VALUE)value = iterated[index]; else value = [index, iterated[index]]; return iterResult(0, value); }); // 21.1.3.27 String.prototype[@@iterator]() - SHAM, TODO defineIterator(String, STRING, Iterators[ARRAY]); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 23.1.5.1 CreateMapIterator Abstract Operation defineStdIterators(Map, MAP, KEY+VALUE, function(iterated, kind){ var keys; if(Map[SHIM])keys = getValues(iterated[COLLECTION_KEYS]); else Map[PROTOTYPE][FOR_EACH].call(iterated, function(val, key){ this.push(key); }, keys = []); set(this, ITER, {o: iterated, k: kind, a: keys, i: 0}); // 23.1.5.2.1 %MapIteratorPrototype%.next() }, function(){ var iter = this[ITER] , iterated = iter.o , keys = iter.a , index = iter.i++ , kind = iter.k , key, value; if(index >= keys.length)return iterResult(1); key = keys[index]; if(kind == KEY) value = key; else if(kind == VALUE)value = iterated.get(key); else value = [key, iterated.get(key)]; return iterResult(0, value); }); // 23.2.5.1 CreateSetIterator Abstract Operation defineStdIterators(Set, SET, VALUE, function(iterated, kind){ var keys; if(Set[SHIM])keys = getValues(iterated[COLLECTION_KEYS]); else Set[PROTOTYPE][FOR_EACH].call(iterated, function(val){ this.push(val); }, keys = []); set(this, ITER, {k: kind, a: keys.reverse(), l: keys.length}); // 23.2.5.2.1 %SetIteratorPrototype%.next() }, function(){ var iter = this[ITER] , keys = iter.a , key; if(!keys.length)return iterResult(1); key = keys.pop(); return iterResult(0, iter.k == KEY+VALUE ? [key, key] : key); }); }(); /****************************************************************************** * Module : timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : binding * ******************************************************************************/ !function(_, toLocaleString){ $define(PROTO + FORCED, FUNCTION, { part: part, by: function(that){ var fn = this , _ = path._ , holder = false , length = arguments.length , isThat = that === _ , i = +!isThat , indent = i , it, args; if(isThat){ it = fn; fn = call; } else it = that; if(length < 2)return ctx(fn, it, -1); args = Array(length - indent); while(length > i)if((args[i - indent] = arguments[i++]) === _)holder = true; return partial(fn, args, length, holder, _, true, it); }, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(ES5Object(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { // ~ ES7 : https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true), // Deprecated name of Array#includes contains: deprecated(createArrayContains(true), ARRAY+SHARP+CONTAINS, ARRAY+SHARP+INCLUDES), turn: turn }); /****************************************************************************** * Module : array_statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !function(){ function setArrayStatics(keys, length){ $define(STATIC, ARRAY, turn.call( array(keys), function(memo, key){ if(key in ArrayProto)memo[key] = ctx(call, ArrayProto[key], length); }, {} )); } setArrayStatics('pop,reverse,shift,keys,values,entries', 1); setArrayStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setArrayStatics('join,slice,concat,push,splice,unshift,sort,' + 'lastIndexOf,reduce,reduceRight,fill,turn'); }(); /****************************************************************************** * Module : number * ******************************************************************************/ !function(){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); $define(PROTO + FORCED, NUMBER, { random: function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; } }); $define(PROTO + FORCED, NUMBER, turn.call( array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(memo, key){ var fn = Math[key]; if(fn)memo[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } }, {} )); }(); /****************************************************************************** * Module : string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : regexp * ******************************************************************************/ // ~ES7 : https://gist.github.com/kangax/9698100 $define(STATIC, REGEXP, { escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); /****************************************************************************** * Module : date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function lz(num){ return num > 9 ? num : '0' + num; } function addLocale(lang, locale){ function split(index){ return turn.call(array(locale.months), function(memo, it){ memo.push(it.replace(flexioRegExp, '$' + index)); }); } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : console * ******************************************************************************/ !function(console){ var $console = turn.call( /** * Methods from: * https://github.com/DeveloperToolsWG/console-object/blob/master/api.md * https://developer.mozilla.org/en-US/docs/Web/API/console */ array('assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,' + 'groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,' + 'table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'), function(memo, key){ var fn = console[key]; memo[key] = function(){ if(enabled && fn)return apply.call(fn, console, arguments); }; }, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } } ), enabled = true; try { framework && delete global.console; } catch(e){} $define(GLOBAL + FORCED, {console: assign($console.log, $console)}); }(global.console || {}); }(Function('return this'), false);
src/components/Preferences.react.js
tomasen/kitematic
import React from 'react/addons'; import metrics from '../utils/MetricsUtil'; import Router from 'react-router'; var Preferences = React.createClass({ mixins: [Router.Navigation], getInitialState: function () { return { closeVMOnQuit: localStorage.getItem('settings.closeVMOnQuit') === 'true', metricsEnabled: metrics.enabled() }; }, handleGoBackClick: function () { this.goBack(); metrics.track('Went Back From Preferences'); }, handleChangeCloseVMOnQuit: function (e) { var checked = e.target.checked; this.setState({ closeVMOnQuit: checked }); localStorage.setItem('settings.closeVMOnQuit', checked); metrics.track('Toggled Close VM On Quit', { close: checked }); }, handleChangeMetricsEnabled: function (e) { var checked = e.target.checked; this.setState({ metricsEnabled: checked }); metrics.setEnabled(checked); metrics.track('Toggled util/MetricsUtil', { enabled: checked }); }, render: function () { return ( <div className="preferences"> <div className="preferences-content"> <a onClick={this.handleGoBackClick}>Go Back</a> <div className="title">VM Settings</div> <div className="option"> <div className="option-name"> Shutdown Linux VM on closing Kitematic </div> <div className="option-value"> <input type="checkbox" checked={this.state.closeVMOnQuit} onChange={this.handleChangeCloseVMOnQuit}/> </div> </div> <div className="title">App Settings</div> <div className="option"> <div className="option-name"> Report anonymous usage analytics </div> <div className="option-value"> <input type="checkbox" checked={this.state.metricsEnabled} onChange={this.handleChangeMetricsEnabled}/> </div> </div> </div> </div> ); } }); module.exports = Preferences;
js/vendor/jquery-1.9.1.min.js
TecHunter/jquery-ui-chat
/*! 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);
src/comment/views/Edit.js
rick-liu/react_readable_frontend
import React from 'react' import { connect } from 'react-redux' import Form from './Form' import { updateComment } from '../actions' const EditComment = ({ active, submit }) => ( active && <Form title="Edit Comment" submitAction={submit}/> ) const mapStateToProps = ({ commentForm }) => ({ active: commentForm.active && commentForm.type === 'edit', submit: updateComment }) export default connect( mapStateToProps )(EditComment)
src/routes/component/index.js
balmbees/overwatch
import React from 'react'; import create from './create'; import show from './show'; export default { path: '/components', children: [ create, show, ], async action({ next }) { // eslint-disable-line const component = await next(); return ( <div> {component} </div> ); }, };
public/docs/api/latest/@stdlib/utils/if-else/benchmark_bundle.js
stdlib-js/www
// modules are defined as an array // [ module function, map of requireuires ] // // map of requireuires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the requireuire for previous bundles (function outer (modules, cache, entry) { // Save the require from previous bundle to this closure if any var previousRequire = typeof require == "function" && require; function findProxyquireifyName() { var deps = Object.keys(modules) .map(function (k) { return modules[k][1]; }); for (var i = 0; i < deps.length; i++) { var pq = deps[i]['proxyquireify']; if (pq) return pq; } } var proxyquireifyName = findProxyquireifyName(); function newRequire(name, jumped){ // Find the proxyquireify module, if present var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Proxyquireify provides a separate cache that is used when inside // a proxyquire call, and is set to null outside a proxyquire call. // This allows the regular caching semantics to work correctly both // inside and outside proxyquire calls while keeping the cached // modules isolated. // When switching from one proxyquire call to another, it clears // the cache to prevent contamination between different sets // of stubs. var currentCache = (pqify && pqify.exports._cache) || cache; if(!currentCache[name]) { if(!modules[name]) { // if we cannot find the the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); // If there are other bundles on this page the require from the // previous one is saved to 'previousRequire'. Repeat this as // many times as there are bundles until the module is found or // we exhaust the require chain. if (previousRequire) return previousRequire(name, true); var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = currentCache[name] = {exports:{}}; // The normal browserify require function var req = function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); }; // The require function substituted for proxyquireify var moduleRequire = function(x){ var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Only try to use the proxyquireify version if it has been `require`d if (pqify && pqify.exports._proxy) { return pqify.exports._proxy(req, x); } else { return req(x); } }; modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry); } return currentCache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); // Override the current require with this new one return newRequire; }) ({1:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],2:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. * * @module @stdlib/array/float32 * * @example * var ctor = require( '@stdlib/array/float32' ); * * var arr = new ctor( 10 ); * // returns <Float32Array> */ // MODULES // var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); var builtin = require( './float32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasFloat32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":33}],3:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of single-precision floating-point numbers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],4:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],5:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. * * @module @stdlib/array/float64 * * @example * var ctor = require( '@stdlib/array/float64' ); * * var arr = new ctor( 10 ); * // returns <Float64Array> */ // MODULES // var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); var builtin = require( './float64array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasFloat64ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":36}],6:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of double-precision floating-point numbers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],7:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. * * @module @stdlib/array/int16 * * @example * var ctor = require( '@stdlib/array/int16' ); * * var arr = new ctor( 10 ); * // returns <Int16Array> */ // MODULES // var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); var builtin = require( './int16array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt16ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":41}],8:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],9:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],10:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. * * @module @stdlib/array/int32 * * @example * var ctor = require( '@stdlib/array/int32' ); * * var arr = new ctor( 10 ); * // returns <Int32Array> */ // MODULES // var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); var builtin = require( './int32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":44}],11:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],12:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],13:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. * * @module @stdlib/array/int8 * * @example * var ctor = require( '@stdlib/array/int8' ); * * var arr = new ctor( 10 ); * // returns <Int8Array> */ // MODULES // var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); var builtin = require( './int8array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt8ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":47}],14:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],15:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],16:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Int8Array = require( '@stdlib/array/int8' ); var Uint8Array = require( '@stdlib/array/uint8' ); var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); var Int16Array = require( '@stdlib/array/int16' ); var Uint16Array = require( '@stdlib/array/uint16' ); var Int32Array = require( '@stdlib/array/int32' ); var Uint32Array = require( '@stdlib/array/uint32' ); var Float32Array = require( '@stdlib/array/float32' ); var Float64Array = require( '@stdlib/array/float64' ); // MAIN // var CTORS = [ [ Float64Array, 'Float64Array' ], [ Float32Array, 'Float32Array' ], [ Int32Array, 'Int32Array' ], [ Uint32Array, 'Uint32Array' ], [ Int16Array, 'Int16Array' ], [ Uint16Array, 'Uint16Array' ], [ Int8Array, 'Int8Array' ], [ Uint8Array, 'Uint8Array' ], [ Uint8ClampedArray, 'Uint8ClampedArray' ] ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],17:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a JSON representation of a typed array. * * @module @stdlib/array/to-json * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var toJSON = require( '@stdlib/array/to-json' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ // MODULES // var toJSON = require( './to_json.js' ); // EXPORTS // module.exports = toJSON; },{"./to_json.js":18}],18:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isTypedArray = require( '@stdlib/assert/is-typed-array' ); var typeName = require( './type.js' ); // MAIN // /** * Returns a JSON representation of a typed array. * * ## Notes * * - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. * * [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson * * @param {TypedArray} arr - typed array to serialize * @throws {TypeError} first argument must be a typed array * @returns {Object} JSON representation * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ function toJSON( arr ) { var out; var i; if ( !isTypedArray( arr ) ) { throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' ); } out = {}; out.type = typeName( arr ); out.data = []; for ( i = 0; i < arr.length; i++ ) { out.data.push( arr[ i ] ); } return out; } // EXPORTS // module.exports = toJSON; },{"./type.js":19,"@stdlib/assert/is-typed-array":165}],19:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var instanceOf = require( '@stdlib/assert/instance-of' ); var ctorName = require( '@stdlib/utils/constructor-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var CTORS = require( './ctors.js' ); // MAIN // /** * Returns the typed array type. * * @private * @param {TypedArray} arr - typed array * @returns {(string|void)} typed array type * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( 5 ); * var str = typeName( arr ); * // returns 'Float64Array' */ function typeName( arr ) { var v; var i; // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) { return CTORS[ i ][ 1 ]; } } // Walk the prototype tree until we find an object having a desired native class... while ( arr ) { v = ctorName( arr ); for ( i = 0; i < CTORS.length; i++ ) { if ( v === CTORS[ i ][ 1 ] ) { return CTORS[ i ][ 1 ]; } } arr = getPrototypeOf( arr ); } } // EXPORTS // module.exports = typeName; },{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":330,"@stdlib/utils/get-prototype-of":353}],20:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint16 * * @example * var ctor = require( '@stdlib/array/uint16' ); * * var arr = new ctor( 10 ); * // returns <Uint16Array> */ // MODULES // var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); var builtin = require( './uint16array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint16ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],21:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 16-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],22:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],23:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint32 * * @example * var ctor = require( '@stdlib/array/uint32' ); * * var arr = new ctor( 10 ); * // returns <Uint32Array> */ // MODULES // var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); var builtin = require( './uint32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],24:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 32-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],25:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],26:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint8 * * @example * var ctor = require( '@stdlib/array/uint8' ); * * var arr = new ctor( 10 ); * // returns <Uint8Array> */ // MODULES // var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); var builtin = require( './uint8array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint8ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],27:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 8-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],28:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],29:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. * * @module @stdlib/array/uint8c * * @example * var ctor = require( '@stdlib/array/uint8c' ); * * var arr = new ctor( 10 ); * // returns <Uint8ClampedArray> */ // MODULES // var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length var builtin = require( './uint8clampedarray.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint8ClampedArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],30:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],31:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],32:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],33:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Float32Array` support. * * @module @stdlib/assert/has-float32array-support * * @example * var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); * * var bool = hasFloat32ArraySupport(); * // returns <boolean> */ // MODULES // var hasFloat32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasFloat32ArraySupport; },{"./main.js":34}],34:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFloat32Array = require( '@stdlib/assert/is-float32array' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var GlobalFloat32Array = require( './float32array.js' ); // MAIN // /** * Tests for native `Float32Array` support. * * @returns {boolean} boolean indicating if an environment has `Float32Array` support * * @example * var bool = hasFloat32ArraySupport(); * // returns <boolean> */ function hasFloat32ArraySupport() { var bool; var arr; if ( typeof GlobalFloat32Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] ); bool = ( isFloat32Array( arr ) && arr[ 0 ] === 1.0 && arr[ 1 ] === 3.140000104904175 && arr[ 2 ] === -3.140000104904175 && arr[ 3 ] === PINF ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasFloat32ArraySupport; },{"./float32array.js":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":242}],35:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],36:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Float64Array` support. * * @module @stdlib/assert/has-float64array-support * * @example * var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); * * var bool = hasFloat64ArraySupport(); * // returns <boolean> */ // MODULES // var hasFloat64ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasFloat64ArraySupport; },{"./main.js":37}],37:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFloat64Array = require( '@stdlib/assert/is-float64array' ); var GlobalFloat64Array = require( './float64array.js' ); // MAIN // /** * Tests for native `Float64Array` support. * * @returns {boolean} boolean indicating if an environment has `Float64Array` support * * @example * var bool = hasFloat64ArraySupport(); * // returns <boolean> */ function hasFloat64ArraySupport() { var bool; var arr; if ( typeof GlobalFloat64Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] ); bool = ( isFloat64Array( arr ) && arr[ 0 ] === 1.0 && arr[ 1 ] === 3.14 && arr[ 2 ] === -3.14 && arr[ 3 ] !== arr[ 3 ] ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasFloat64ArraySupport; },{"./float64array.js":35,"@stdlib/assert/is-float64array":100}],38:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Dummy function. * * @private */ function foo() { // No-op... } // EXPORTS // module.exports = foo; },{}],39:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native function `name` support. * * @module @stdlib/assert/has-function-name-support * * @example * var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); * * var bool = hasFunctionNameSupport(); * // returns <boolean> */ // MODULES // var hasFunctionNameSupport = require( './main.js' ); // EXPORTS // module.exports = hasFunctionNameSupport; },{"./main.js":40}],40:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var foo = require( './foo.js' ); // MAIN // /** * Tests for native function `name` support. * * @returns {boolean} boolean indicating if an environment has function `name` support * * @example * var bool = hasFunctionNameSupport(); * // returns <boolean> */ function hasFunctionNameSupport() { return ( foo.name === 'foo' ); } // EXPORTS // module.exports = hasFunctionNameSupport; },{"./foo.js":38}],41:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Int16Array` support. * * @module @stdlib/assert/has-int16array-support * * @example * var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); * * var bool = hasInt16ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt16ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt16ArraySupport; },{"./main.js":43}],42:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],43:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInt16Array = require( '@stdlib/assert/is-int16array' ); var INT16_MAX = require( '@stdlib/constants/int16/max' ); var INT16_MIN = require( '@stdlib/constants/int16/min' ); var GlobalInt16Array = require( './int16array.js' ); // MAIN // /** * Tests for native `Int16Array` support. * * @returns {boolean} boolean indicating if an environment has `Int16Array` support * * @example * var bool = hasInt16ArraySupport(); * // returns <boolean> */ function hasInt16ArraySupport() { var bool; var arr; if ( typeof GlobalInt16Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] ); bool = ( isInt16Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT16_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt16ArraySupport; },{"./int16array.js":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":243,"@stdlib/constants/int16/min":244}],44:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Int32Array` support. * * @module @stdlib/assert/has-int32array-support * * @example * var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); * * var bool = hasInt32ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt32ArraySupport; },{"./main.js":46}],45:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],46:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInt32Array = require( '@stdlib/assert/is-int32array' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var INT32_MIN = require( '@stdlib/constants/int32/min' ); var GlobalInt32Array = require( './int32array.js' ); // MAIN // /** * Tests for native `Int32Array` support. * * @returns {boolean} boolean indicating if an environment has `Int32Array` support * * @example * var bool = hasInt32ArraySupport(); * // returns <boolean> */ function hasInt32ArraySupport() { var bool; var arr; if ( typeof GlobalInt32Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] ); bool = ( isInt32Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT32_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt32ArraySupport; },{"./int32array.js":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":245,"@stdlib/constants/int32/min":246}],47:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Int8Array` support. * * @module @stdlib/assert/has-int8array-support * * @example * var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); * * var bool = hasInt8ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt8ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt8ArraySupport; },{"./main.js":49}],48:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],49:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInt8Array = require( '@stdlib/assert/is-int8array' ); var INT8_MAX = require( '@stdlib/constants/int8/max' ); var INT8_MIN = require( '@stdlib/constants/int8/min' ); var GlobalInt8Array = require( './int8array.js' ); // MAIN // /** * Tests for native `Int8Array` support. * * @returns {boolean} boolean indicating if an environment has `Int8Array` support * * @example * var bool = hasInt8ArraySupport(); * // returns <boolean> */ function hasInt8ArraySupport() { var bool; var arr; if ( typeof GlobalInt8Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] ); bool = ( isInt8Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT8_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt8ArraySupport; },{"./int8array.js":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":247,"@stdlib/constants/int8/min":248}],50:[function(require,module,exports){ (function (Buffer){(function (){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; }).call(this)}).call(this,require("buffer").Buffer) },{"buffer":424}],51:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Buffer` support. * * @module @stdlib/assert/has-node-buffer-support * * @example * var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' ); * * var bool = hasNodeBufferSupport(); * // returns <boolean> */ // MODULES // var hasNodeBufferSupport = require( './main.js' ); // EXPORTS // module.exports = hasNodeBufferSupport; },{"./main.js":52}],52:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var GlobalBuffer = require( './buffer.js' ); // MAIN // /** * Tests for native `Buffer` support. * * @returns {boolean} boolean indicating if an environment has `Buffer` support * * @example * var bool = hasNodeBufferSupport(); * // returns <boolean> */ function hasNodeBufferSupport() { var bool; var b; if ( typeof GlobalBuffer !== 'function' ) { return false; } // Test basic support... try { if ( typeof GlobalBuffer.from === 'function' ) { b = GlobalBuffer.from( [ 1, 2, 3, 4 ] ); } else { b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array) } bool = ( isBuffer( b ) && b[ 0 ] === 1 && b[ 1 ] === 2 && b[ 2 ] === 3 && b[ 3 ] === 4 ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasNodeBufferSupport; },{"./buffer.js":50,"@stdlib/assert/is-buffer":88}],53:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test whether an object has a specified property. * * @module @stdlib/assert/has-own-property * * @example * var hasOwnProp = require( '@stdlib/assert/has-own-property' ); * * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'boop' ); * // returns true * * bool = hasOwnProp( beep, 'bop' ); * // returns false */ // MODULES // var hasOwnProp = require( './main.js' ); // EXPORTS // module.exports = hasOwnProp; },{"./main.js":54}],54:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // FUNCTIONS // var has = Object.prototype.hasOwnProperty; // MAIN // /** * Tests if an object has a specified property. * * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object has a specified property * * @example * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'bap' ); * // returns false */ function hasOwnProp( value, property ) { if ( value === void 0 || value === null ) { return false; } return has.call( value, property ); } // EXPORTS // module.exports = hasOwnProp; },{}],55:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Symbol` support. * * @module @stdlib/assert/has-symbol-support * * @example * var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' ); * * var bool = hasSymbolSupport(); * // returns <boolean> */ // MODULES // var hasSymbolSupport = require( './main.js' ); // EXPORTS // module.exports = hasSymbolSupport; },{"./main.js":56}],56:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests for native `Symbol` support. * * @returns {boolean} boolean indicating if an environment has `Symbol` support * * @example * var bool = hasSymbolSupport(); * // returns <boolean> */ function hasSymbolSupport() { return ( typeof Symbol === 'function' && typeof Symbol( 'foo' ) === 'symbol' ); } // EXPORTS // module.exports = hasSymbolSupport; },{}],57:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `toStringTag` support. * * @module @stdlib/assert/has-tostringtag-support * * @example * var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' ); * * var bool = hasToStringTagSupport(); * // returns <boolean> */ // MODULES // var hasToStringTagSupport = require( './main.js' ); // EXPORTS // module.exports = hasToStringTagSupport; },{"./main.js":58}],58:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasSymbols = require( '@stdlib/assert/has-symbol-support' ); // VARIABLES // var FLG = hasSymbols(); // MAIN // /** * Tests for native `toStringTag` support. * * @returns {boolean} boolean indicating if an environment has `toStringTag` support * * @example * var bool = hasToStringTagSupport(); * // returns <boolean> */ function hasToStringTagSupport() { return ( FLG && typeof Symbol.toStringTag === 'symbol' ); } // EXPORTS // module.exports = hasToStringTagSupport; },{"@stdlib/assert/has-symbol-support":55}],59:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Uint16Array` support. * * @module @stdlib/assert/has-uint16array-support * * @example * var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); * * var bool = hasUint16ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint16ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint16ArraySupport; },{"./main.js":60}],60:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isUint16Array = require( '@stdlib/assert/is-uint16array' ); var UINT16_MAX = require( '@stdlib/constants/uint16/max' ); var GlobalUint16Array = require( './uint16array.js' ); // MAIN // /** * Tests for native `Uint16Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint16Array` support * * @example * var bool = hasUint16ArraySupport(); * // returns <boolean> */ function hasUint16ArraySupport() { var bool; var arr; if ( typeof GlobalUint16Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ]; arr = new GlobalUint16Array( arr ); bool = ( isUint16Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint16ArraySupport; },{"./uint16array.js":61,"@stdlib/assert/is-uint16array":168,"@stdlib/constants/uint16/max":249}],61:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],62:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Uint32Array` support. * * @module @stdlib/assert/has-uint32array-support * * @example * var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); * * var bool = hasUint32ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint32ArraySupport; },{"./main.js":63}],63:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var GlobalUint32Array = require( './uint32array.js' ); // MAIN // /** * Tests for native `Uint32Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint32Array` support * * @example * var bool = hasUint32ArraySupport(); * // returns <boolean> */ function hasUint32ArraySupport() { var bool; var arr; if ( typeof GlobalUint32Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ]; arr = new GlobalUint32Array( arr ); bool = ( isUint32Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint32ArraySupport; },{"./uint32array.js":64,"@stdlib/assert/is-uint32array":170,"@stdlib/constants/uint32/max":250}],64:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],65:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Uint8Array` support. * * @module @stdlib/assert/has-uint8array-support * * @example * var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); * * var bool = hasUint8ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint8ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint8ArraySupport; },{"./main.js":66}],66:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isUint8Array = require( '@stdlib/assert/is-uint8array' ); var UINT8_MAX = require( '@stdlib/constants/uint8/max' ); var GlobalUint8Array = require( './uint8array.js' ); // MAIN // /** * Tests for native `Uint8Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint8Array` support * * @example * var bool = hasUint8ArraySupport(); * // returns <boolean> */ function hasUint8ArraySupport() { var bool; var arr; if ( typeof GlobalUint8Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ]; arr = new GlobalUint8Array( arr ); bool = ( isUint8Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint8ArraySupport; },{"./uint8array.js":67,"@stdlib/assert/is-uint8array":172,"@stdlib/constants/uint8/max":251}],67:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],68:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test for native `Uint8ClampedArray` support. * * @module @stdlib/assert/has-uint8clampedarray-support * * @example * var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); * * var bool = hasUint8ClampedArraySupport(); * // returns <boolean> */ // MODULES // var hasUint8ClampedArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint8ClampedArraySupport; },{"./main.js":69}],69:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); var GlobalUint8ClampedArray = require( './uint8clampedarray.js' ); // MAIN // /** * Tests for native `Uint8ClampedArray` support. * * @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support * * @example * var bool = hasUint8ClampedArraySupport(); * // returns <boolean> */ function hasUint8ClampedArraySupport() { // eslint-disable-line id-length var bool; var arr; if ( typeof GlobalUint8ClampedArray !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] ); bool = ( isUint8ClampedArray( arr ) && arr[ 0 ] === 0 && // clamped arr[ 1 ] === 0 && arr[ 2 ] === 1 && arr[ 3 ] === 3 && // round to nearest arr[ 4 ] === 5 && // round to nearest arr[ 5 ] === 255 && arr[ 6 ] === 255 // clamped ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint8ClampedArraySupport; },{"./uint8clampedarray.js":70,"@stdlib/assert/is-uint8clampedarray":174}],70:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],71:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test whether a value has in its prototype chain a specified constructor as a prototype property. * * @module @stdlib/assert/instance-of * * @example * var instanceOf = require( '@stdlib/assert/instance-of' ); * * var bool = instanceOf( [], Array ); * // returns true * * bool = instanceOf( {}, Object ); // exception * // returns true * * bool = instanceOf( 'beep', String ); * // returns false * * bool = instanceOf( null, Object ); * // returns false * * bool = instanceOf( 5, Object ); * // returns false */ // MODULES // var instanceOf = require( './main.js' ); // EXPORTS // module.exports = instanceOf; },{"./main.js":72}],72:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests whether a value has in its prototype chain a specified constructor as a prototype property. * * @param {*} value - value to test * @param {Function} constructor - constructor to test against * @throws {TypeError} constructor must be callable * @returns {boolean} boolean indicating whether a value is an instance of a provided constructor * * @example * var bool = instanceOf( [], Array ); * // returns true * * @example * var bool = instanceOf( {}, Object ); // exception * // returns true * * @example * var bool = instanceOf( 'beep', String ); * // returns false * * @example * var bool = instanceOf( null, Object ); * // returns false * * @example * var bool = instanceOf( 5, Object ); * // returns false */ function instanceOf( value, constructor ) { // TODO: replace with `isCallable` check if ( typeof constructor !== 'function' ) { throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' ); } return ( value instanceof constructor ); } // EXPORTS // module.exports = instanceOf; },{}],73:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArguments = require( './main.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Detects whether an environment returns the expected internal class of the `arguments` object. * * @private * @returns {boolean} boolean indicating whether an environment behaves as expected * * @example * var bool = detect(); * // returns <boolean> */ function detect() { return isArguments( arguments ); } // MAIN // bool = detect(); // EXPORTS // module.exports = bool; },{"./main.js":75}],74:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an `arguments` object. * * @module @stdlib/assert/is-arguments * * @example * var isArguments = require( '@stdlib/assert/is-arguments' ); * * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * bool = isArguments( [] ); * // returns false */ // MODULES // var hasArgumentsClass = require( './detect.js' ); var main = require( './main.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var isArguments; if ( hasArgumentsClass ) { isArguments = main; } else { isArguments = polyfill; } // EXPORTS // module.exports = isArguments; },{"./detect.js":73,"./main.js":75,"./polyfill.js":76}],75:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // MAIN // /** * Tests whether a value is an `arguments` object. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `arguments` object * * @example * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * @example * var bool = isArguments( [] ); * // returns false */ function isArguments( value ) { return ( nativeClass( value ) === '[object Arguments]' ); } // EXPORTS // module.exports = isArguments; },{"@stdlib/utils/native-class":391}],76:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); var isArray = require( '@stdlib/assert/is-array' ); var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/uint32/max' ); // MAIN // /** * Tests whether a value is an `arguments` object. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `arguments` object * * @example * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * @example * var bool = isArguments( [] ); * // returns false */ function isArguments( value ) { return ( value !== null && typeof value === 'object' && !isArray( value ) && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH && hasOwnProp( value, 'callee' ) && !isEnumerableProperty( value, 'callee' ) ); } // EXPORTS // module.exports = isArguments; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":250,"@stdlib/math/base/assert/is-integer":254}],77:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is array-like. * * @module @stdlib/assert/is-array-like * * @example * var isArrayLike = require( '@stdlib/assert/is-array-like' ); * * var bool = isArrayLike( [] ); * // returns true * * bool = isArrayLike( { 'length': 10 } ); * // returns true * * bool = isArrayLike( 'beep' ); * // returns true */ // MODULES // var isArrayLike = require( './main.js' ); // EXPORTS // module.exports = isArrayLike; },{"./main.js":78}],78:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' ); // MAIN // /** * Tests if a value is array-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is array-like * * @example * var bool = isArrayLike( [] ); * // returns true * * @example * var bool = isArrayLike( {'length':10} ); * // returns true */ function isArrayLike( value ) { return ( value !== void 0 && value !== null && typeof value !== 'function' && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH ); } // EXPORTS // module.exports = isArrayLike; },{"@stdlib/constants/array/max-array-length":235,"@stdlib/math/base/assert/is-integer":254}],79:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an array. * * @module @stdlib/assert/is-array * * @example * var isArray = require( '@stdlib/assert/is-array' ); * * var bool = isArray( [] ); * // returns true * * bool = isArray( {} ); * // returns false */ // MODULES // var isArray = require( './main.js' ); // EXPORTS // module.exports = isArray; },{"./main.js":80}],80:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var f; // FUNCTIONS // /** * Tests if a value is an array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an array * * @example * var bool = isArray( [] ); * // returns true * * @example * var bool = isArray( {} ); * // returns false */ function isArray( value ) { return ( nativeClass( value ) === '[object Array]' ); } // MAIN // if ( Array.isArray ) { f = Array.isArray; } else { f = isArray; } // EXPORTS // module.exports = f; },{"@stdlib/utils/native-class":391}],81:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a boolean. * * @module @stdlib/assert/is-boolean * * @example * var isBoolean = require( '@stdlib/assert/is-boolean' ); * * var bool = isBoolean( false ); * // returns true * * bool = isBoolean( new Boolean( false ) ); * // returns true * * @example * // Use interface to check for boolean primitives... * var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; * * var bool = isBoolean( false ); * // returns true * * bool = isBoolean( new Boolean( true ) ); * // returns false * * @example * // Use interface to check for boolean objects... * var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject; * * var bool = isBoolean( true ); * // returns false * * bool = isBoolean( new Boolean( false ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isBoolean = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isBoolean, 'isPrimitive', isPrimitive ); setReadOnly( isBoolean, 'isObject', isObject ); // EXPORTS // module.exports = isBoolean; },{"./main.js":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":338}],82:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a boolean. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a boolean * * @example * var bool = isBoolean( false ); * // returns true * * @example * var bool = isBoolean( true ); * // returns true * * @example * var bool = isBoolean( new Boolean( false ) ); * // returns true * * @example * var bool = isBoolean( new Boolean( true ) ); * // returns true */ function isBoolean( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isBoolean; },{"./object.js":83,"./primitive.js":84}],83:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2serialize.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a boolean object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a boolean object * * @example * var bool = isBoolean( true ); * // returns false * * @example * var bool = isBoolean( new Boolean( false ) ); * // returns true */ function isBoolean( value ) { if ( typeof value === 'object' ) { if ( value instanceof Boolean ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object Boolean]' ); } return false; } // EXPORTS // module.exports = isBoolean; },{"./try2serialize.js":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":391}],84:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests if a value is a boolean primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a boolean primitive * * @example * var bool = isBoolean( true ); * // returns true * * @example * var bool = isBoolean( false ); * // returns true * * @example * var bool = isBoolean( new Boolean( true ) ); * // returns false */ function isBoolean( value ) { return ( typeof value === 'boolean' ); } // EXPORTS // module.exports = isBoolean; },{}],85:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // eslint-disable-next-line stdlib/no-redeclare var toString = Boolean.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{}],86:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare // MAIN // /** * Attempts to serialize a value to a string. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a value can be serialized */ function test( value ) { try { toString.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./tostring.js":85}],87:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // EXPORTS // module.exports = true; },{}],88:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Buffer instance. * * @module @stdlib/assert/is-buffer * * @example * var isBuffer = require( '@stdlib/assert/is-buffer' ); * * var v = isBuffer( new Buffer( 'beep' ) ); * // returns true * * v = isBuffer( {} ); * // returns false */ // MODULES // var isBuffer = require( './main.js' ); // EXPORTS // module.exports = isBuffer; },{"./main.js":89}],89:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObjectLike = require( '@stdlib/assert/is-object-like' ); // MAIN // /** * Tests if a value is a Buffer instance. * * @param {*} value - value to validate * @returns {boolean} boolean indicating if a value is a Buffer instance * * @example * var v = isBuffer( new Buffer( 'beep' ) ); * // returns true * * @example * var v = isBuffer( new Buffer( [1,2,3,4] ) ); * // returns true * * @example * var v = isBuffer( {} ); * // returns false * * @example * var v = isBuffer( [] ); * // returns false */ function isBuffer( value ) { return ( isObjectLike( value ) && ( // eslint-disable-next-line no-underscore-dangle value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7) ( value.constructor && // WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions typeof value.constructor.isBuffer === 'function' && value.constructor.isBuffer( value ) ) ) ); } // EXPORTS // module.exports = isBuffer; },{"@stdlib/assert/is-object-like":143}],90:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a collection. * * @module @stdlib/assert/is-collection * * @example * var isCollection = require( '@stdlib/assert/is-collection' ); * * var bool = isCollection( [] ); * // returns true * * bool = isCollection( {} ); * // returns false */ // MODULES // var isCollection = require( './main.js' ); // EXPORTS // module.exports = isCollection; },{"./main.js":91}],91:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' ); // MAIN // /** * Tests if a value is a collection. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is a collection * * @example * var bool = isCollection( [] ); * // returns true * * @example * var bool = isCollection( {} ); * // returns false */ function isCollection( value ) { return ( typeof value === 'object' && value !== null && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH ); } // EXPORTS // module.exports = isCollection; },{"@stdlib/constants/array/max-typed-array-length":236,"@stdlib/math/base/assert/is-integer":254}],92:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isEnum = require( './native.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10. * * @private * @returns {boolean} boolean indicating whether an environment has the bug */ function detect() { return !isEnum.call( 'beep', '0' ); } // MAIN // bool = detect(); // EXPORTS // module.exports = bool; },{"./native.js":95}],93:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test whether an object's own property is enumerable. * * @module @stdlib/assert/is-enumerable-property * * @example * var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); * * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ // MODULES // var isEnumerableProperty = require( './main.js' ); // EXPORTS // module.exports = isEnumerableProperty; },{"./main.js":94}],94:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ); var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var isEnum = require( './native.js' ); var hasStringEnumBug = require( './has_string_enumerability_bug.js' ); // MAIN // /** * Tests if an object's own property is enumerable. * * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object property is enumerable * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ function isEnumerableProperty( value, property ) { var bool; if ( value === void 0 || value === null ) { return false; } bool = isEnum.call( value, property ); if ( !bool && hasStringEnumBug && isString( value ) ) { // Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above. property = +property; return ( !isnan( property ) && isInteger( property ) && property >= 0 && property < value.length ); } return bool; } // EXPORTS // module.exports = isEnumerableProperty; },{"./has_string_enumerability_bug.js":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],95:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests if an object's own property is enumerable. * * @private * @name isEnumerableProperty * @type {Function} * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object property is enumerable * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ var isEnumerableProperty = Object.prototype.propertyIsEnumerable; // EXPORTS // module.exports = isEnumerableProperty; },{}],96:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an `Error` object. * * @module @stdlib/assert/is-error * * @example * var isError = require( '@stdlib/assert/is-error' ); * * var bool = isError( new Error( 'beep' ) ); * // returns true * * bool = isError( {} ); * // returns false */ // MODULES // var isError = require( './main.js' ); // EXPORTS // module.exports = isError; },{"./main.js":97}],97:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var nativeClass = require( '@stdlib/utils/native-class' ); // MAIN // /** * Tests if a value is an `Error` object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `Error` object * * @example * var bool = isError( new Error( 'beep' ) ); * // returns true * * @example * var bool = isError( {} ); * // returns false */ function isError( value ) { if ( typeof value !== 'object' || value === null ) { return false; } // Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)... if ( value instanceof Error ) { return true; } // Walk the prototype tree until we find an object having the desired native class... while ( value ) { if ( nativeClass( value ) === '[object Error]' ) { return true; } value = getPrototypeOf( value ); } return false; } // EXPORTS // module.exports = isError; },{"@stdlib/utils/get-prototype-of":353,"@stdlib/utils/native-class":391}],98:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Float32Array. * * @module @stdlib/assert/is-float32array * * @example * var isFloat32Array = require( '@stdlib/assert/is-float32array' ); * * var bool = isFloat32Array( new Float32Array( 10 ) ); * // returns true * * bool = isFloat32Array( [] ); * // returns false */ // MODULES // var isFloat32Array = require( './main.js' ); // EXPORTS // module.exports = isFloat32Array; },{"./main.js":99}],99:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Float32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Float32Array * * @example * var bool = isFloat32Array( new Float32Array( 10 ) ); * // returns true * * @example * var bool = isFloat32Array( [] ); * // returns false */ function isFloat32Array( value ) { return ( ( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Float32Array]' ); } // EXPORTS // module.exports = isFloat32Array; },{"@stdlib/utils/native-class":391}],100:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Float64Array. * * @module @stdlib/assert/is-float64array * * @example * var isFloat64Array = require( '@stdlib/assert/is-float64array' ); * * var bool = isFloat64Array( new Float64Array( 10 ) ); * // returns true * * bool = isFloat64Array( [] ); * // returns false */ // MODULES // var isFloat64Array = require( './main.js' ); // EXPORTS // module.exports = isFloat64Array; },{"./main.js":101}],101:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Float64Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Float64Array * * @example * var bool = isFloat64Array( new Float64Array( 10 ) ); * // returns true * * @example * var bool = isFloat64Array( [] ); * // returns false */ function isFloat64Array( value ) { return ( ( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Float64Array]' ); } // EXPORTS // module.exports = isFloat64Array; },{"@stdlib/utils/native-class":391}],102:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a function. * * @module @stdlib/assert/is-function * * @example * var isFunction = require( '@stdlib/assert/is-function' ); * * function beep() { * return 'beep'; * } * * var bool = isFunction( beep ); * // returns true */ // MODULES // var isFunction = require( './main.js' ); // EXPORTS // module.exports = isFunction; },{"./main.js":103}],103:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var typeOf = require( '@stdlib/utils/type-of' ); // MAIN // /** * Tests if a value is a function. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a function * * @example * function beep() { * return 'beep'; * } * * var bool = isFunction( beep ); * // returns true */ function isFunction( value ) { // Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists. return ( typeOf( value ) === 'function' ); } // EXPORTS // module.exports = isFunction; },{"@stdlib/utils/type-of":418}],104:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an Int16Array. * * @module @stdlib/assert/is-int16array * * @example * var isInt16Array = require( '@stdlib/assert/is-int16array' ); * * var bool = isInt16Array( new Int16Array( 10 ) ); * // returns true * * bool = isInt16Array( [] ); * // returns false */ // MODULES // var isInt16Array = require( './main.js' ); // EXPORTS // module.exports = isInt16Array; },{"./main.js":105}],105:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int16Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int16Array * * @example * var bool = isInt16Array( new Int16Array( 10 ) ); * // returns true * * @example * var bool = isInt16Array( [] ); * // returns false */ function isInt16Array( value ) { return ( ( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int16Array]' ); } // EXPORTS // module.exports = isInt16Array; },{"@stdlib/utils/native-class":391}],106:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an Int32Array. * * @module @stdlib/assert/is-int32array * * @example * var isInt32Array = require( '@stdlib/assert/is-int32array' ); * * var bool = isInt32Array( new Int32Array( 10 ) ); * // returns true * * bool = isInt32Array( [] ); * // returns false */ // MODULES // var isInt32Array = require( './main.js' ); // EXPORTS // module.exports = isInt32Array; },{"./main.js":107}],107:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int32Array * * @example * var bool = isInt32Array( new Int32Array( 10 ) ); * // returns true * * @example * var bool = isInt32Array( [] ); * // returns false */ function isInt32Array( value ) { return ( ( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int32Array]' ); } // EXPORTS // module.exports = isInt32Array; },{"@stdlib/utils/native-class":391}],108:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an Int8Array. * * @module @stdlib/assert/is-int8array * * @example * var isInt8Array = require( '@stdlib/assert/is-int8array' ); * * var bool = isInt8Array( new Int8Array( 10 ) ); * // returns true * * bool = isInt8Array( [] ); * // returns false */ // MODULES // var isInt8Array = require( './main.js' ); // EXPORTS // module.exports = isInt8Array; },{"./main.js":109}],109:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int8Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int8Array * * @example * var bool = isInt8Array( new Int8Array( 10 ) ); * // returns true * * @example * var bool = isInt8Array( [] ); * // returns false */ function isInt8Array( value ) { return ( ( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int8Array]' ); } // EXPORTS // module.exports = isInt8Array; },{"@stdlib/utils/native-class":391}],110:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an integer. * * @module @stdlib/assert/is-integer * * @example * var isInteger = require( '@stdlib/assert/is-integer' ); * * var bool = isInteger( 5.0 ); * // returns true * * bool = isInteger( new Number( 5.0 ) ); * // returns true * * bool = isInteger( -3.14 ); * // returns false * * bool = isInteger( null ); * // returns false * * @example * // Use interface to check for integer primitives... * var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; * * var bool = isInteger( -3.0 ); * // returns true * * bool = isInteger( new Number( -3.0 ) ); * // returns false * * @example * // Use interface to check for integer objects... * var isInteger = require( '@stdlib/assert/is-integer' ).isObject; * * var bool = isInteger( 3.0 ); * // returns false * * bool = isInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isInteger, 'isPrimitive', isPrimitive ); setReadOnly( isInteger, 'isObject', isObject ); // EXPORTS // module.exports = isInteger; },{"./main.js":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":338}],111:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var isInt = require( '@stdlib/math/base/assert/is-integer' ); // MAIN // /** * Tests if a number primitive is an integer value. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a number primitive is an integer value */ function isInteger( value ) { return ( value < PINF && value > NINF && isInt( value ) ); } // EXPORTS // module.exports = isInteger; },{"@stdlib/constants/float64/ninf":241,"@stdlib/constants/float64/pinf":242,"@stdlib/math/base/assert/is-integer":254}],112:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is an integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an integer * * @example * var bool = isInteger( 5.0 ); * // returns true * * @example * var bool = isInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isInteger( -3.14 ); * // returns false * * @example * var bool = isInteger( null ); * // returns false */ function isInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isInteger; },{"./object.js":113,"./primitive.js":114}],113:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; var isInt = require( './integer.js' ); // MAIN // /** * Tests if a value is a number object having an integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having an integer value * * @example * var bool = isInteger( 3.0 ); * // returns false * * @example * var bool = isInteger( new Number( 3.0 ) ); * // returns true */ function isInteger( value ) { return ( isNumber( value ) && isInt( value.valueOf() ) ); } // EXPORTS // module.exports = isInteger; },{"./integer.js":111,"@stdlib/assert/is-number":137}],114:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; var isInt = require( './integer.js' ); // MAIN // /** * Tests if a value is a number primitive having an integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having an integer value * * @example * var bool = isInteger( -3.0 ); * // returns true * * @example * var bool = isInteger( new Number( -3.0 ) ); * // returns false */ function isInteger( value ) { return ( isNumber( value ) && isInt( value ) ); } // EXPORTS // module.exports = isInteger; },{"./integer.js":111,"@stdlib/assert/is-number":137}],115:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Uint8Array = require( '@stdlib/array/uint8' ); var Uint16Array = require( '@stdlib/array/uint16' ); // MAIN // var ctors = { 'uint16': Uint16Array, 'uint8': Uint8Array }; // EXPORTS // module.exports = ctors; },{"@stdlib/array/uint16":20,"@stdlib/array/uint8":26}],116:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a boolean indicating if an environment is little endian. * * @module @stdlib/assert/is-little-endian * * @example * var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' ); * * var bool = IS_LITTLE_ENDIAN; * // returns <boolean> */ // MODULES // var IS_LITTLE_ENDIAN = require( './main.js' ); // EXPORTS // module.exports = IS_LITTLE_ENDIAN; },{"./main.js":117}],117:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var ctors = require( './ctors.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Returns a boolean indicating if an environment is little endian. * * @private * @returns {boolean} boolean indicating if an environment is little endian * * @example * var bool = isLittleEndian(); * // returns <boolean> */ function isLittleEndian() { var uint16view; var uint8view; uint16view = new ctors[ 'uint16' ]( 1 ); /* * Set the uint16 view to a value having distinguishable lower and higher order words. * * 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52) */ uint16view[ 0 ] = 0x1234; // Create a uint8 view on top of the uint16 buffer: uint8view = new ctors[ 'uint8' ]( uint16view.buffer ); // If little endian, the least significant byte will be first... return ( uint8view[ 0 ] === 0x34 ); } // MAIN // bool = isLittleEndian(); // EXPORTS // module.exports = bool; },{"./ctors.js":115}],118:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is `NaN`. * * @module @stdlib/assert/is-nan * * @example * var isnan = require( '@stdlib/assert/is-nan' ); * * var bool = isnan( NaN ); * // returns true * * bool = isnan( new Number( NaN ) ); * // returns true * * bool = isnan( 3.14 ); * // returns false * * bool = isnan( null ); * // returns false * * @example * var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; * * var bool = isnan( NaN ); * // returns true * * bool = isnan( 3.14 ); * // returns false * * bool = isnan( new Number( NaN ) ); * // returns false * * @example * var isnan = require( '@stdlib/assert/is-nan' ).isObject; * * var bool = isnan( NaN ); * // returns false * * bool = isnan( new Number( NaN ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isnan = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isnan, 'isPrimitive', isPrimitive ); setReadOnly( isnan, 'isObject', isObject ); // EXPORTS // module.exports = isnan; },{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":338}],119:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is `NaN`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is `NaN` * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( new Number( NaN ) ); * // returns true * * @example * var bool = isnan( 3.14 ); * // returns false * * @example * var bool = isnan( null ); * // returns false */ function isnan( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isnan; },{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; var isNan = require( '@stdlib/math/base/assert/is-nan' ); // MAIN // /** * Tests if a value is a number object having a value of `NaN`. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a value of `NaN` * * @example * var bool = isnan( NaN ); * // returns false * * @example * var bool = isnan( new Number( NaN ) ); * // returns true */ function isnan( value ) { return ( isNumber( value ) && isNan( value.valueOf() ) ); } // EXPORTS // module.exports = isnan; },{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":256}],121:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; var isNan = require( '@stdlib/math/base/assert/is-nan' ); // MAIN // /** * Tests if a value is a `NaN` number primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a `NaN` number primitive * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( 3.14 ); * // returns false * * @example * var bool = isnan( new Number( NaN ) ); * // returns false */ function isnan( value ) { return ( isNumber( value ) && isNan( value ) ); } // EXPORTS // module.exports = isnan; },{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":256}],122:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is Node stream-like. * * @module @stdlib/assert/is-node-stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' ); * * var stream = transformStream(); * * var bool = isNodeStreamLike( stream ); * // returns true * * bool = isNodeStreamLike( {} ); * // returns false */ // MODULES // var isNodeStreamLike = require( './main.js' ); // EXPORTS // module.exports = isNodeStreamLike; },{"./main.js":123}],123:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests if a value is Node stream-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is Node stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * var stream = transformStream(); * * var bool = isNodeStreamLike( stream ); * // returns true * * bool = isNodeStreamLike( {} ); * // returns false */ function isNodeStreamLike( value ) { return ( // Must be an object: value !== null && typeof value === 'object' && // Should be an event emitter: typeof value.on === 'function' && typeof value.once === 'function' && typeof value.emit === 'function' && typeof value.addListener === 'function' && typeof value.removeListener === 'function' && typeof value.removeAllListeners === 'function' && // Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams): typeof value.pipe === 'function' ); } // EXPORTS // module.exports = isNodeStreamLike; },{}],124:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is Node writable stream-like. * * @module @stdlib/assert/is-node-writable-stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' ); * * var stream = transformStream(); * * var bool = isNodeWritableStreamLike( stream ); * // returns true * * bool = isNodeWritableStreamLike( {} ); * // returns false */ // MODULES // var isNodeWritableStreamLike = require( './main.js' ); // EXPORTS // module.exports = isNodeWritableStreamLike; },{"./main.js":125}],125:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable no-underscore-dangle */ 'use strict'; // MODULES // var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' ); // MAIN // /** * Tests if a value is Node writable stream-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is Node writable stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * var stream = transformStream(); * * var bool = isNodeWritableStreamLike( stream ); * // returns true * * bool = isNodeWritableStreamLike( {} ); * // returns false */ function isNodeWritableStreamLike( value ) { return ( // Must be stream-like: isNodeStreamLike( value ) && // Should have writable stream methods: typeof value._write === 'function' && // Should have writable stream state: typeof value._writableState === 'object' ); } // EXPORTS // module.exports = isNodeWritableStreamLike; },{"@stdlib/assert/is-node-stream-like":122}],126:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an array-like object containing only nonnegative integers. * * @module @stdlib/assert/is-nonnegative-integer-array * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ); * * var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] ); * // returns false * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives; * * var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] ); * // returns false * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects; * * var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] ); * // returns false */ // MODULES // var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-like-function' ); // MAIN // var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger ); setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) ); setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) ); // EXPORTS // module.exports = isNonNegativeIntegerArray; },{"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/assert/tools/array-like-function":179,"@stdlib/utils/define-nonenumerable-read-only-property":338}],127:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a nonnegative integer. * * @module @stdlib/assert/is-nonnegative-integer * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ); * * var bool = isNonNegativeInteger( 5.0 ); * // returns true * * bool = isNonNegativeInteger( new Number( 5.0 ) ); * // returns true * * bool = isNonNegativeInteger( -5.0 ); * // returns false * * bool = isNonNegativeInteger( 3.14 ); * // returns false * * bool = isNonNegativeInteger( null ); * // returns false * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; * * var bool = isNonNegativeInteger( 3.0 ); * // returns true * * bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns false * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject; * * var bool = isNonNegativeInteger( 3.0 ); * // returns false * * bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNonNegativeInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive ); setReadOnly( isNonNegativeInteger, 'isObject', isObject ); // EXPORTS // module.exports = isNonNegativeInteger; },{"./main.js":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":338}],128:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a nonnegative integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a nonnegative integer * * @example * var bool = isNonNegativeInteger( 5.0 ); * // returns true * * @example * var bool = isNonNegativeInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isNonNegativeInteger( -5.0 ); * // returns false * * @example * var bool = isNonNegativeInteger( 3.14 ); * // returns false * * @example * var bool = isNonNegativeInteger( null ); * // returns false */ function isNonNegativeInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"./object.js":129,"./primitive.js":130}],129:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isObject; // MAIN // /** * Tests if a value is a number object having a nonnegative integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value * * @example * var bool = isNonNegativeInteger( 3.0 ); * // returns false * * @example * var bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns true */ function isNonNegativeInteger( value ) { return ( isInteger( value ) && value.valueOf() >= 0 ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"@stdlib/assert/is-integer":110}],130:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a nonnegative integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value * * @example * var bool = isNonNegativeInteger( 3.0 ); * // returns true * * @example * var bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns false */ function isNonNegativeInteger( value ) { return ( isInteger( value ) && value >= 0 ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"@stdlib/assert/is-integer":110}],131:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a nonnegative number. * * @module @stdlib/assert/is-nonnegative-number * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ); * * var bool = isNonNegativeNumber( 5.0 ); * // returns true * * bool = isNonNegativeNumber( new Number( 5.0 ) ); * // returns true * * bool = isNonNegativeNumber( 3.14 ); * // returns true * * bool = isNonNegativeNumber( -5.0 ); * // returns false * * bool = isNonNegativeNumber( null ); * // returns false * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; * * var bool = isNonNegativeNumber( 3.0 ); * // returns true * * bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns false * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject; * * var bool = isNonNegativeNumber( 3.0 ); * // returns false * * bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNonNegativeNumber = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive ); setReadOnly( isNonNegativeNumber, 'isObject', isObject ); // EXPORTS // module.exports = isNonNegativeNumber; },{"./main.js":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":338}],132:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a nonnegative number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a nonnegative number * * @example * var bool = isNonNegativeNumber( 5.0 ); * // returns true * * @example * var bool = isNonNegativeNumber( new Number( 5.0 ) ); * // returns true * * @example * var bool = isNonNegativeNumber( 3.14 ); * // returns true * * @example * var bool = isNonNegativeNumber( -5.0 ); * // returns false * * @example * var bool = isNonNegativeNumber( null ); * // returns false */ function isNonNegativeNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"./object.js":133,"./primitive.js":134}],133:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; // MAIN // /** * Tests if a value is a number object having a nonnegative value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value * * @example * var bool = isNonNegativeNumber( 3.0 ); * // returns false * * @example * var bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns true */ function isNonNegativeNumber( value ) { return ( isNumber( value ) && value.valueOf() >= 0.0 ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"@stdlib/assert/is-number":137}],134:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a nonnegative value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value * * @example * var bool = isNonNegativeNumber( 3.0 ); * // returns true * * @example * var bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns false */ function isNonNegativeNumber( value ) { return ( isNumber( value ) && value >= 0.0 ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"@stdlib/assert/is-number":137}],135:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is `null`. * * @module @stdlib/assert/is-null * * @example * var isNull = require( '@stdlib/assert/is-null' ); * * var value = null; * * var bool = isNull( value ); * // returns true */ // MODULES // var isNull = require( './main.js' ); // EXPORTS // module.exports = isNull; },{"./main.js":136}],136:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests if a value is `null`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is null * * @example * var bool = isNull( null ); * // returns true * * bool = isNull( true ); * // returns false */ function isNull( value ) { return value === null; } // EXPORTS // module.exports = isNull; },{}],137:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a number. * * @module @stdlib/assert/is-number * * @example * var isNumber = require( '@stdlib/assert/is-number' ); * * var bool = isNumber( 3.14 ); * // returns true * * bool = isNumber( new Number( 3.14 ) ); * // returns true * * bool = isNumber( NaN ); * // returns true * * bool = isNumber( null ); * // returns false * * @example * var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; * * var bool = isNumber( 3.14 ); * // returns true * * bool = isNumber( NaN ); * // returns true * * bool = isNumber( new Number( 3.14 ) ); * // returns false * * @example * var isNumber = require( '@stdlib/assert/is-number' ).isObject; * * var bool = isNumber( 3.14 ); * // returns false * * bool = isNumber( new Number( 3.14 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNumber = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNumber, 'isPrimitive', isPrimitive ); setReadOnly( isNumber, 'isObject', isObject ); // EXPORTS // module.exports = isNumber; },{"./main.js":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":338}],138:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a number * * @example * var bool = isNumber( 3.14 ); * // returns true * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns true * * @example * var bool = isNumber( NaN ); * // returns true * * @example * var bool = isNumber( null ); * // returns false */ function isNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNumber; },{"./object.js":139,"./primitive.js":140}],139:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var Number = require( '@stdlib/number/ctor' ); var test = require( './try2serialize.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a number object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object * * @example * var bool = isNumber( 3.14 ); * // returns false * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns true */ function isNumber( value ) { if ( typeof value === 'object' ) { if ( value instanceof Number ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object Number]' ); } return false; } // EXPORTS // module.exports = isNumber; },{"./try2serialize.js":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":271,"@stdlib/utils/native-class":391}],140:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests if a value is a number primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive * * @example * var bool = isNumber( 3.14 ); * // returns true * * @example * var bool = isNumber( NaN ); * // returns true * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns false */ function isNumber( value ) { return ( typeof value === 'number' ); } // EXPORTS // module.exports = isNumber; },{}],141:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Number = require( '@stdlib/number/ctor' ); // MAIN // // eslint-disable-next-line stdlib/no-redeclare var toString = Number.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{"@stdlib/number/ctor":271}],142:[function(require,module,exports){ arguments[4][86][0].apply(exports,arguments) },{"./tostring.js":141,"dup":86}],143:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is object-like. * * @module @stdlib/assert/is-object-like * * @example * var isObjectLike = require( '@stdlib/assert/is-object-like' ); * * var bool = isObjectLike( {} ); * // returns true * * bool = isObjectLike( [] ); * // returns true * * bool = isObjectLike( null ); * // returns false * * @example * var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray; * * var bool = isObjectLike( [ {}, [] ] ); * // returns true * * bool = isObjectLike( [ {}, '3.0' ] ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-function' ); var isObjectLike = require( './main.js' ); // MAIN // setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) ); // EXPORTS // module.exports = isObjectLike; },{"./main.js":144,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":338}],144:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests if a value is object-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is object-like * * @example * var bool = isObjectLike( {} ); * // returns true * * @example * var bool = isObjectLike( [] ); * // returns true * * @example * var bool = isObjectLike( null ); * // returns false */ function isObjectLike( value ) { return ( value !== null && typeof value === 'object' ); } // EXPORTS // module.exports = isObjectLike; },{}],145:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an object. * * @module @stdlib/assert/is-object * * @example * var isObject = require( '@stdlib/assert/is-object' ); * * var bool = isObject( {} ); * // returns true * * bool = isObject( true ); * // returns false */ // MODULES // var isObject = require( './main.js' ); // EXPORTS // module.exports = isObject; },{"./main.js":146}],146:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); // MAIN // /** * Tests if a value is an object; e.g., `{}`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an object * * @example * var bool = isObject( {} ); * // returns true * * @example * var bool = isObject( null ); * // returns false */ function isObject( value ) { return ( typeof value === 'object' && value !== null && !isArray( value ) ); } // EXPORTS // module.exports = isObject; },{"@stdlib/assert/is-array":79}],147:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a plain object. * * @module @stdlib/assert/is-plain-object * * @example * var isPlainObject = require( '@stdlib/assert/is-plain-object' ); * * var bool = isPlainObject( {} ); * // returns true * * bool = isPlainObject( null ); * // returns false */ // MODULES // var isPlainObject = require( './main.js' ); // EXPORTS // module.exports = isPlainObject; },{"./main.js":148}],148:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-object' ); var isFunction = require( '@stdlib/assert/is-function' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var objectPrototype = Object.prototype; // FUNCTIONS // /** * Tests that an object only has own properties. * * @private * @param {Object} obj - value to test * @returns {boolean} boolean indicating if an object only has own properties */ function ownProps( obj ) { var key; // NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing). for ( key in obj ) { if ( !hasOwnProp( obj, key ) ) { return false; } } return true; } // MAIN // /** * Tests if a value is a plain object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a plain object * * @example * var bool = isPlainObject( {} ); * // returns true * * @example * var bool = isPlainObject( null ); * // returns false */ function isPlainObject( value ) { var proto; // Screen for obvious non-objects... if ( !isObject( value ) ) { return false; } // Objects with no prototype (e.g., `Object.create( null )`) are plain... proto = getPrototypeOf( value ); if ( !proto ) { return true; } // Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object... return ( // Cannot have own `constructor` property: !hasOwnProp( value, 'constructor' ) && // Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing): hasOwnProp( proto, 'constructor' ) && isFunction( proto.constructor ) && nativeClass( proto.constructor ) === '[object Function]' && // Test for object-specific method: hasOwnProp( proto, 'isPrototypeOf' ) && isFunction( proto.isPrototypeOf ) && ( // Test if the prototype matches the global `Object` prototype (same realm): proto === objectPrototype || // Test that all properties are own properties (cross-realm; *most* likely a plain object): ownProps( value ) ) ); } // EXPORTS // module.exports = isPlainObject; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":353,"@stdlib/utils/native-class":391}],149:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a positive integer. * * @module @stdlib/assert/is-positive-integer * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ); * * var bool = isPositiveInteger( 5.0 ); * // returns true * * bool = isPositiveInteger( new Number( 5.0 ) ); * // returns true * * bool = isPositiveInteger( -5.0 ); * // returns false * * bool = isPositiveInteger( 3.14 ); * // returns false * * bool = isPositiveInteger( null ); * // returns false * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; * * var bool = isPositiveInteger( 3.0 ); * // returns true * * bool = isPositiveInteger( new Number( 3.0 ) ); * // returns false * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject; * * var bool = isPositiveInteger( 3.0 ); * // returns false * * bool = isPositiveInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isPositiveInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive ); setReadOnly( isPositiveInteger, 'isObject', isObject ); // EXPORTS // module.exports = isPositiveInteger; },{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":338}],150:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a positive integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a positive integer * * @example * var bool = isPositiveInteger( 5.0 ); * // returns true * * @example * var bool = isPositiveInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isPositiveInteger( 0.0 ); * // returns false * * @example * var bool = isPositiveInteger( -5.0 ); * // returns false * * @example * var bool = isPositiveInteger( 3.14 ); * // returns false * * @example * var bool = isPositiveInteger( null ); * // returns false */ function isPositiveInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isPositiveInteger; },{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isObject; // MAIN // /** * Tests if a value is a number object having a positive integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a positive integer value * * @example * var bool = isPositiveInteger( 3.0 ); * // returns false * * @example * var bool = isPositiveInteger( new Number( 3.0 ) ); * // returns true */ function isPositiveInteger( value ) { return ( isInteger( value ) && value.valueOf() > 0.0 ); } // EXPORTS // module.exports = isPositiveInteger; },{"@stdlib/assert/is-integer":110}],152:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a positive integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value * * @example * var bool = isPositiveInteger( 3.0 ); * // returns true * * @example * var bool = isPositiveInteger( new Number( 3.0 ) ); * // returns false */ function isPositiveInteger( value ) { return ( isInteger( value ) && value > 0.0 ); } // EXPORTS // module.exports = isPositiveInteger; },{"@stdlib/assert/is-integer":110}],153:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var exec = RegExp.prototype.exec; // non-generic // EXPORTS // module.exports = exec; },{}],154:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a regular expression. * * @module @stdlib/assert/is-regexp * * @example * var isRegExp = require( '@stdlib/assert/is-regexp' ); * * var bool = isRegExp( /\.+/ ); * // returns true * * bool = isRegExp( {} ); * // returns false */ // MODULES // var isRegExp = require( './main.js' ); // EXPORTS // module.exports = isRegExp; },{"./main.js":155}],155:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2exec.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a regular expression. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a regular expression * * @example * var bool = isRegExp( /\.+/ ); * // returns true * * @example * var bool = isRegExp( {} ); * // returns false */ function isRegExp( value ) { if ( typeof value === 'object' ) { if ( value instanceof RegExp ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object RegExp]' ); } return false; } // EXPORTS // module.exports = isRegExp; },{"./try2exec.js":156,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":391}],156:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var exec = require( './exec.js' ); // MAIN // /** * Attempts to call a `RegExp` method. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if able to call a `RegExp` method */ function test( value ) { try { exec.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./exec.js":153}],157:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is an array of strings. * * @module @stdlib/assert/is-string-array * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ); * * var bool = isStringArray( [ 'abc', 'def' ] ); * // returns true * * bool = isStringArray( [ 'abc', 123 ] ); * // returns false * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; * * var bool = isStringArray( [ 'abc', 'def' ] ); * // returns true * * bool = isStringArray( [ 'abc', new String( 'def' ) ] ); * // returns false * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ).objects; * * var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] ); * // returns true * * bool = isStringArray( [ new String( 'abc' ), 'def' ] ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-function' ); var isString = require( '@stdlib/assert/is-string' ); // MAIN // var isStringArray = arrayfun( isString ); setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) ); setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) ); // EXPORTS // module.exports = isStringArray; },{"@stdlib/assert/is-string":158,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":338}],158:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a string. * * @module @stdlib/assert/is-string * * @example * var isString = require( '@stdlib/assert/is-string' ); * * var bool = isString( 'beep' ); * // returns true * * bool = isString( new String( 'beep' ) ); * // returns true * * bool = isString( 5 ); * // returns false * * @example * var isString = require( '@stdlib/assert/is-string' ).isObject; * * var bool = isString( new String( 'beep' ) ); * // returns true * * bool = isString( 'beep' ); * // returns false * * @example * var isString = require( '@stdlib/assert/is-string' ).isPrimitive; * * var bool = isString( 'beep' ); * // returns true * * bool = isString( new String( 'beep' ) ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isString = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isString, 'isPrimitive', isPrimitive ); setReadOnly( isString, 'isObject', isObject ); // EXPORTS // module.exports = isString; },{"./main.js":159,"./object.js":160,"./primitive.js":161,"@stdlib/utils/define-nonenumerable-read-only-property":338}],159:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a string. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a string * * @example * var bool = isString( new String( 'beep' ) ); * // returns true * * @example * var bool = isString( 'beep' ); * // returns true */ function isString( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isString; },{"./object.js":160,"./primitive.js":161}],160:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2valueof.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a string object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a string object * * @example * var bool = isString( new String( 'beep' ) ); * // returns true * * @example * var bool = isString( 'beep' ); * // returns false */ function isString( value ) { if ( typeof value === 'object' ) { if ( value instanceof String ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object String]' ); } return false; } // EXPORTS // module.exports = isString; },{"./try2valueof.js":162,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":391}],161:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests if a value is a string primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a string primitive * * @example * var bool = isString( 'beep' ); * // returns true * * @example * var bool = isString( new String( 'beep' ) ); * // returns false */ function isString( value ) { return ( typeof value === 'string' ); } // EXPORTS // module.exports = isString; },{}],162:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare // MAIN // /** * Attempts to extract a string value. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a string can be extracted */ function test( value ) { try { valueOf.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./valueof.js":163}],163:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // eslint-disable-next-line stdlib/no-redeclare var valueOf = String.prototype.valueOf; // non-generic // EXPORTS // module.exports = valueOf; },{}],164:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Int8Array = require( '@stdlib/array/int8' ); var Uint8Array = require( '@stdlib/array/uint8' ); var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); var Int16Array = require( '@stdlib/array/int16' ); var Uint16Array = require( '@stdlib/array/uint16' ); var Int32Array = require( '@stdlib/array/int32' ); var Uint32Array = require( '@stdlib/array/uint32' ); var Float32Array = require( '@stdlib/array/float32' ); var Float64Array = require( '@stdlib/array/float64' ); // MAIN // var CTORS = [ Float64Array, Float32Array, Int32Array, Uint32Array, Int16Array, Uint16Array, Int8Array, Uint8Array, Uint8ClampedArray ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],165:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a typed array. * * @module @stdlib/assert/is-typed-array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * var isTypedArray = require( '@stdlib/assert/is-typed-array' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ // MODULES // var isTypedArray = require( './main.js' ); // EXPORTS // module.exports = isTypedArray; },{"./main.js":166}],166:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); var fcnName = require( '@stdlib/utils/function-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); var Float64Array = require( '@stdlib/array/float64' ); var CTORS = require( './ctors.js' ); var NAMES = require( './names.json' ); // VARIABLES // // Abstract `TypedArray` class: var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len // Ensure abstract typed array class has expected name: TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy; // FUNCTIONS // /** * Dummy constructor. * * @private */ function Dummy() {} // eslint-disable-line no-empty-function // MAIN // /** * Tests if a value is a typed array. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a typed array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ function isTypedArray( value ) { var v; var i; if ( typeof value !== 'object' || value === null ) { return false; } // Check for the abstract class... if ( value instanceof TypedArray ) { return true; } // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( value instanceof CTORS[ i ] ) { return true; } } // Walk the prototype tree until we find an object having a desired class... while ( value ) { v = ctorName( value ); for ( i = 0; i < NAMES.length; i++ ) { if ( NAMES[ i ] === v ) { return true; } } value = getPrototypeOf( value ); } return false; } // EXPORTS // module.exports = isTypedArray; },{"./ctors.js":164,"./names.json":167,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":330,"@stdlib/utils/function-name":350,"@stdlib/utils/get-prototype-of":353}],167:[function(require,module,exports){ module.exports=[ "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array" ] },{}],168:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Uint16Array. * * @module @stdlib/assert/is-uint16array * * @example * var isUint16Array = require( '@stdlib/assert/is-uint16array' ); * * var bool = isUint16Array( new Uint16Array( 10 ) ); * // returns true * * bool = isUint16Array( [] ); * // returns false */ // MODULES // var isUint16Array = require( './main.js' ); // EXPORTS // module.exports = isUint16Array; },{"./main.js":169}],169:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint16Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint16Array * * @example * var bool = isUint16Array( new Uint16Array( 10 ) ); * // returns true * * @example * var bool = isUint16Array( [] ); * // returns false */ function isUint16Array( value ) { return ( ( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint16Array]' ); } // EXPORTS // module.exports = isUint16Array; },{"@stdlib/utils/native-class":391}],170:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Uint32Array. * * @module @stdlib/assert/is-uint32array * * @example * var isUint32Array = require( '@stdlib/assert/is-uint32array' ); * * var bool = isUint32Array( new Uint32Array( 10 ) ); * // returns true * * bool = isUint32Array( [] ); * // returns false */ // MODULES // var isUint32Array = require( './main.js' ); // EXPORTS // module.exports = isUint32Array; },{"./main.js":171}],171:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint32Array * * @example * var bool = isUint32Array( new Uint32Array( 10 ) ); * // returns true * * @example * var bool = isUint32Array( [] ); * // returns false */ function isUint32Array( value ) { return ( ( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint32Array]' ); } // EXPORTS // module.exports = isUint32Array; },{"@stdlib/utils/native-class":391}],172:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Uint8Array. * * @module @stdlib/assert/is-uint8array * * @example * var isUint8Array = require( '@stdlib/assert/is-uint8array' ); * * var bool = isUint8Array( new Uint8Array( 10 ) ); * // returns true * * bool = isUint8Array( [] ); * // returns false */ // MODULES // var isUint8Array = require( './main.js' ); // EXPORTS // module.exports = isUint8Array; },{"./main.js":173}],173:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint8Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint8Array * * @example * var bool = isUint8Array( new Uint8Array( 10 ) ); * // returns true * * @example * var bool = isUint8Array( [] ); * // returns false */ function isUint8Array( value ) { return ( ( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint8Array]' ); } // EXPORTS // module.exports = isUint8Array; },{"@stdlib/utils/native-class":391}],174:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a value is a Uint8ClampedArray. * * @module @stdlib/assert/is-uint8clampedarray * * @example * var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); * * var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) ); * // returns true * * bool = isUint8ClampedArray( [] ); * // returns false */ // MODULES // var isUint8ClampedArray = require( './main.js' ); // EXPORTS // module.exports = isUint8ClampedArray; },{"./main.js":175}],175:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint8ClampedArray. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint8ClampedArray * * @example * var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) ); * // returns true * * @example * var bool = isUint8ClampedArray( [] ); * // returns false */ function isUint8ClampedArray( value ) { return ( ( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint8ClampedArray]' ); } // EXPORTS // module.exports = isUint8ClampedArray; },{"@stdlib/utils/native-class":391}],176:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); // MAIN // /** * Returns a function which tests if every element in an array passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arrayfcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arrayfcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArray( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arrayfcn; },{"@stdlib/assert/is-array":79}],177:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a function which tests if every element in an array passes a test condition. * * @module @stdlib/assert/tools/array-function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * var arrayfcn = require( '@stdlib/assert/tools/array-function' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arrayfcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ // MODULES // var arrayfcn = require( './arrayfcn.js' ); // EXPORTS // module.exports = arrayfcn; },{"./arrayfcn.js":176}],178:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArrayLike = require( '@stdlib/assert/is-array-like' ); // MAIN // /** * Returns a function which tests if every element in an array-like object passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array-like object function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arraylikefcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arraylikefcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array-like object passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArrayLike( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arraylikefcn; },{"@stdlib/assert/is-array-like":77}],179:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a function which tests if every element in an array-like object passes a test condition. * * @module @stdlib/assert/tools/array-like-function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arraylikefcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ // MODULES // var arraylikefcn = require( './arraylikefcn.js' ); // EXPORTS // module.exports = arraylikefcn; },{"./arraylikefcn.js":178}],180:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var createHarness = require( './harness' ); var harness = require( './get_harness.js' ); // VARIABLES // var listeners = []; // FUNCTIONS // /** * Callback invoked when a harness finishes running all benchmarks. * * @private */ function done() { var len; var f; var i; len = listeners.length; // Inform all the listeners that the harness has finished... for ( i = 0; i < len; i++ ) { f = listeners.shift(); f(); } } /** * Creates a results stream. * * @private * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ function createStream( options ) { var stream; var bench; var opts; if ( arguments.length ) { opts = options; } else { opts = {}; } // If we have already created a harness, calling this function simply creates another results stream... if ( harness.cached ) { bench = harness(); return bench.createStream( opts ); } stream = new TransformStream( opts ); opts.stream = stream; // Create a harness which uses the created output stream: harness( opts, done ); return stream; } /** * Adds a listener for when a harness finishes running all benchmarks. * * @private * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ function onFinish( clbk ) { var i; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' ); } // Allow adding a listener only once... for ( i = 0; i < listeners.length; i++ ) { if ( clbk === listeners[ i ] ) { throw new Error( 'invalid argument. Attempted to add duplicate listener.' ); } } listeners.push( clbk ); } // MAIN // /** * Runs a benchmark. * * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @returns {Benchmark} benchmark harness * * @example * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ function bench( name, options, benchmark ) { var h = harness( done ); if ( arguments.length < 2 ) { h( name ); } else if ( arguments.length === 2 ) { h( name, options ); } else { h( name, options, benchmark ); } return bench; } /** * Creates a benchmark harness. * * @name createHarness * @memberof bench * @type {Function} * @param {Options} [options] - harness options * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness */ setReadOnly( bench, 'createHarness', createHarness ); /** * Creates a results stream. * * @name createStream * @memberof bench * @type {Function} * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ setReadOnly( bench, 'createStream', createStream ); /** * Adds a listener for when a harness finishes running all benchmarks. * * @name onFinish * @memberof bench * @type {Function} * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ setReadOnly( bench, 'onFinish', onFinish ); // EXPORTS // module.exports = bench; },{"./get_harness.js":202,"./harness":203,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":314,"@stdlib/utils/define-nonenumerable-read-only-property":338}],181:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Generates an assertion. * * @private * @param {boolean} ok - assertion outcome * @param {Options} opts - options */ function assert( ok, opts ) { /* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used var result; var err; result = { 'id': this._count, 'ok': ok, 'skip': opts.skip, 'todo': opts.todo, 'name': opts.message || '(unnamed assert)', 'operator': opts.operator }; if ( hasOwnProp( opts, 'actual' ) ) { result.actual = opts.actual; } if ( hasOwnProp( opts, 'expected' ) ) { result.expected = opts.expected; } if ( !ok ) { result.error = opts.error || new Error( this.name ); err = new Error( 'exception' ); // TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215) } this._count += 1; this.emit( 'result', result ); } // EXPORTS // module.exports = assert; },{"@stdlib/assert/has-own-property":53}],182:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // EXPORTS // module.exports = clearTimeout; },{}],183:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var trim = require( '@stdlib/string/trim' ); var replace = require( '@stdlib/string/replace' ); var EOL = require( '@stdlib/regexp/eol' ).REGEXP; // VARIABLES // var RE_COMMENT = /^#\s*/; // MAIN // /** * Writes a comment. * * @private * @param {string} msg - comment message */ function comment( msg ) { /* eslint-disable no-invalid-this */ var lines; var i; msg = trim( msg ); lines = msg.split( EOL ); for ( i = 0; i < lines.length; i++ ) { msg = trim( lines[ i ] ); msg = replace( msg, RE_COMMENT, '' ); this.emit( 'result', msg ); } } // EXPORTS // module.exports = comment; },{"@stdlib/regexp/eol":298,"@stdlib/string/replace":320,"@stdlib/string/trim":322}],184:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that `actual` is deeply equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ function deepEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' ); // TODO: implement } // EXPORTS // module.exports = deepEqual; },{}],185:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nextTick = require( './../utils/next_tick.js' ); // MAIN // /** * Ends a benchmark. * * @private */ function end() { /* eslint-disable no-invalid-this */ var self = this; if ( this._ended ) { this.fail( '.end() called more than once' ); } else { // Prevents releasing the zalgo when running synchronous benchmarks. nextTick( onTick ); } this._ended = true; this._running = false; /** * Callback invoked upon a subsequent tick of the event loop. * * @private */ function onTick() { self.emit( 'end' ); } } // EXPORTS // module.exports = end; },{"./../utils/next_tick.js":222}],186:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns a `boolean` indicating if a benchmark has ended. * * @private * @returns {boolean} boolean indicating if a benchmark has ended */ function ended() { /* eslint-disable no-invalid-this */ return this._ended; } // EXPORTS // module.exports = ended; },{}],187:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that `actual` is strictly equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ function equal( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this._assert( actual === expected, { 'message': msg || 'should be equal', 'operator': 'equal', 'expected': expected, 'actual': actual }); } // EXPORTS // module.exports = equal; },{}],188:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Forcefully ends a benchmark. * * @private * @returns {void} */ function exit() { /* eslint-disable no-invalid-this */ if ( this._exited ) { // If we have already "exited", do not create more failing assertions when one should suffice... return; } // Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion. if ( !this._ended ) { this._exited = true; this.fail( 'benchmark exited without ending' ); // Allow running benchmarks to call `end` on their own... if ( !this._running ) { this.end(); } } } // EXPORTS // module.exports = exit; },{}],189:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Generates a failing assertion. * * @private * @param {string} msg - message */ function fail( msg ) { /* eslint-disable no-invalid-this */ this._assert( false, { 'message': msg, 'operator': 'fail' }); } // EXPORTS // module.exports = fail; },{}],190:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var EventEmitter = require( 'events' ).EventEmitter; var inherit = require( '@stdlib/utils/inherit' ); var defineProperty = require( '@stdlib/utils/define-property' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var tic = require( '@stdlib/time/tic' ); var toc = require( '@stdlib/time/toc' ); var run = require( './run.js' ); var exit = require( './exit.js' ); var ended = require( './ended.js' ); var assert = require( './assert.js' ); var comment = require( './comment.js' ); var skip = require( './skip.js' ); var todo = require( './todo.js' ); var fail = require( './fail.js' ); var pass = require( './pass.js' ); var ok = require( './ok.js' ); var notOk = require( './not_ok.js' ); var equal = require( './equal.js' ); var notEqual = require( './not_equal.js' ); var deepEqual = require( './deep_equal.js' ); var notDeepEqual = require( './not_deep_equal.js' ); var end = require( './end.js' ); // MAIN // /** * Benchmark constructor. * * @constructor * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {boolean} opts.skip - boolean indicating whether to skip a benchmark * @param {PositiveInteger} opts.iterations - number of iterations * @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @returns {Benchmark} Benchmark instance * * @example * var bench = new Benchmark( 'beep', function benchmark( b ) { * var x; * var i; * b.comment( 'Running benchmarks...' ); * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.comment( 'Finished running benchmarks.' ); * b.end(); * }); */ function Benchmark( name, opts, benchmark ) { var hasTicked; var hasTocked; var self; var time; if ( !( this instanceof Benchmark ) ) { return new Benchmark( name, opts, benchmark ); } self = this; hasTicked = false; hasTocked = false; EventEmitter.call( this ); // Private properties: setReadOnly( this, '_benchmark', benchmark ); setReadOnly( this, '_skip', opts.skip ); defineProperty( this, '_ended', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_running', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_exited', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_count', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': 0 }); // Read-only: setReadOnly( this, 'name', name ); setReadOnly( this, 'tic', start ); setReadOnly( this, 'toc', stop ); setReadOnly( this, 'iterations', opts.iterations ); setReadOnly( this, 'timeout', opts.timeout ); return this; /** * Starts a benchmark timer. * * ## Notes * * - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results. * - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`. * - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values. * * @private */ function start() { if ( hasTicked ) { self.fail( '.tic() called more than once' ); } else { self.emit( 'tic' ); hasTicked = true; time = tic(); } } /** * Stops a benchmark timer. * * @private * @returns {void} */ function stop() { var elapsed; var secs; var rate; var out; if ( hasTicked === false ) { return self.fail( '.toc() called before .tic()' ); } elapsed = toc( time ); if ( hasTocked ) { return self.fail( '.toc() called more than once' ); } hasTocked = true; self.emit( 'toc' ); secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 ); rate = self.iterations / secs; out = { 'ok': true, 'operator': 'result', 'iterations': self.iterations, 'elapsed': secs, 'rate': rate }; self.emit( 'result', out ); } } /* * Inherit from the `EventEmitter` prototype. */ inherit( Benchmark, EventEmitter ); /** * Runs a benchmark. * * @private * @name run * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'run', run ); /** * Forcefully ends a benchmark. * * @private * @name exit * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'exit', exit ); /** * Returns a `boolean` indicating if a benchmark has ended. * * @private * @name ended * @memberof Benchmark.prototype * @type {Function} * @returns {boolean} boolean indicating if a benchmark has ended */ setReadOnly( Benchmark.prototype, 'ended', ended ); /** * Generates an assertion. * * @private * @name _assert * @memberof Benchmark.prototype * @type {Function} * @param {boolean} ok - assertion outcome * @param {Options} opts - options */ setReadOnly( Benchmark.prototype, '_assert', assert ); /** * Writes a comment. * * @name comment * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - comment message */ setReadOnly( Benchmark.prototype, 'comment', comment ); /** * Generates an assertion which will be skipped. * * @name skip * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'skip', skip ); /** * Generates an assertion which should be implemented. * * @name todo * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'todo', todo ); /** * Generates a failing assertion. * * @name fail * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'fail', fail ); /** * Generates a passing assertion. * * @name pass * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'pass', pass ); /** * Asserts that a `value` is truthy. * * @name ok * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'ok', ok ); /** * Asserts that a `value` is falsy. * * @name notOk * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notOk', notOk ); /** * Asserts that `actual` is strictly equal to `expected`. * * @name equal * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'equal', equal ); /** * Asserts that `actual` is not strictly equal to `expected`. * * @name notEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notEqual', notEqual ); /** * Asserts that `actual` is deeply equal to `expected`. * * @name deepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual ); /** * Asserts that `actual` is not deeply equal to `expected`. * * @name notDeepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual ); /** * Ends a benchmark. * * @name end * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'end', end ); // EXPORTS // module.exports = Benchmark; },{"./assert.js":181,"./comment.js":183,"./deep_equal.js":184,"./end.js":185,"./ended.js":186,"./equal.js":187,"./exit.js":188,"./fail.js":189,"./not_deep_equal.js":191,"./not_equal.js":192,"./not_ok.js":193,"./ok.js":194,"./pass.js":195,"./run.js":196,"./skip.js":198,"./todo.js":199,"@stdlib/time/tic":324,"@stdlib/time/toc":328,"@stdlib/utils/define-nonenumerable-read-only-property":338,"@stdlib/utils/define-property":345,"@stdlib/utils/inherit":370,"events":423}],191:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that `actual` is not deeply equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ function notDeepEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' ); // TODO: implement } // EXPORTS // module.exports = notDeepEqual; },{}],192:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that `actual` is not strictly equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ function notEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this._assert( actual !== expected, { 'message': msg || 'should not be equal', 'operator': 'notEqual', 'expected': expected, 'actual': actual }); } // EXPORTS // module.exports = notEqual; },{}],193:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that a `value` is falsy. * * @private * @param {*} value - value * @param {string} [msg] - message */ function notOk( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !value, { 'message': msg || 'should be falsy', 'operator': 'notOk', 'expected': false, 'actual': value }); } // EXPORTS // module.exports = notOk; },{}],194:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Asserts that a `value` is truthy. * * @private * @param {*} value - value * @param {string} [msg] - message */ function ok( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !!value, { 'message': msg || 'should be truthy', 'operator': 'ok', 'expected': true, 'actual': value }); } // EXPORTS // module.exports = ok; },{}],195:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Generates a passing assertion. * * @private * @param {string} msg - message */ function pass( msg ) { /* eslint-disable no-invalid-this */ this._assert( true, { 'message': msg, 'operator': 'pass' }); } // EXPORTS // module.exports = pass; },{}],196:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var timeout = require( './set_timeout.js' ); var clear = require( './clear_timeout.js' ); // MAIN // /** * Runs a benchmark. * * @private * @returns {void} */ function run() { /* eslint-disable no-invalid-this */ var self; var id; if ( this._skip ) { this.comment( 'SKIP '+this.name ); return this.end(); } if ( !this._benchmark ) { this.comment( 'TODO '+this.name ); return this.end(); } self = this; this._running = true; id = timeout( onTimeout, this.timeout ); this.once( 'end', endTimeout ); this.emit( 'prerun' ); this._benchmark( this ); this.emit( 'run' ); /** * Callback invoked once a timeout ends. * * @private */ function onTimeout() { self.fail( 'benchmark timed out after '+self.timeout+'ms' ); } /** * Clears a timeout. * * @private */ function endTimeout() { clear( id ); } } // EXPORTS // module.exports = run; },{"./clear_timeout.js":182,"./set_timeout.js":197}],197:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // EXPORTS // module.exports = setTimeout; },{}],198:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Generates an assertion which will be skipped. * * @private * @param {*} value - value * @param {string} msg - message */ function skip( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( true, { 'message': msg, 'operator': 'skip', 'skip': true }); } // EXPORTS // module.exports = skip; },{}],199:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Generates an assertion which should be implemented. * * @private * @param {*} value - value * @param {string} msg - message */ function todo( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !!value, { 'message': msg, 'operator': 'todo', 'todo': true }); } // EXPORTS // module.exports = todo; },{}],200:[function(require,module,exports){ module.exports={ "skip": false, "iterations": null, "repeats": 3, "timeout": 300000 } },{}],201:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var pick = require( '@stdlib/utils/pick' ); var omit = require( '@stdlib/utils/omit' ); var noop = require( '@stdlib/utils/noop' ); var createHarness = require( './harness' ); var logStream = require( './log' ); var canEmitExit = require( './utils/can_emit_exit.js' ); var proc = require( './utils/process.js' ); // MAIN // /** * Creates a benchmark harness which supports closing when a process exits. * * @private * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Stream} [options.stream] - output writable stream * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var proc = require( 'process' ); * var bench = createExitHarness( onFinish ); * * function onFinish() { * bench.close(); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createExitHarness().createStream(); * stream.pipe( stdout ); */ function createExitHarness() { var exitCode; var pipeline; var harness; var options; var stream; var topts; var opts; var clbk; if ( arguments.length === 0 ) { options = {}; clbk = noop; } else if ( arguments.length === 1 ) { if ( isFunction( arguments[ 0 ] ) ) { options = {}; clbk = arguments[ 0 ]; } else if ( isObject( arguments[ 0 ] ) ) { options = arguments[ 0 ]; clbk = noop; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' ); } } else { options = arguments[ 0 ]; if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } clbk = arguments[ 1 ]; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' ); } } opts = {}; if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } if ( hasOwnProp( options, 'stream' ) ) { opts.stream = options.stream; if ( !isNodeWritableStreamLike( opts.stream ) ) { throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' ); } } exitCode = 0; // Create a new harness: topts = pick( opts, [ 'autoclose' ] ); harness = createHarness( topts, done ); // Create a results stream: topts = omit( options, [ 'autoclose', 'stream' ] ); stream = harness.createStream( topts ); // Pipe results to an output stream: pipeline = stream.pipe( opts.stream || logStream() ); // If a process can emit an 'exit' event, capture errors in order to set the exit code... if ( canEmitExit ) { pipeline.on( 'error', onError ); proc.on( 'exit', onExit ); } return harness; /** * Callback invoked when a harness finishes. * * @private * @returns {void} */ function done() { return clbk(); } /** * Callback invoked upon a stream `error` event. * * @private * @param {Error} error - error object */ function onError() { exitCode = 1; } /** * Callback invoked upon an `exit` event. * * @private * @param {integer} code - exit code */ function onExit( code ) { if ( code !== 0 ) { // Allow the process to exit... return; } harness.close(); proc.exit( exitCode || harness.exitCode ); } } // EXPORTS // module.exports = createExitHarness; },{"./harness":203,"./log":209,"./utils/can_emit_exit.js":220,"./utils/process.js":223,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":398,"@stdlib/utils/omit":400,"@stdlib/utils/pick":402}],202:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var canEmitExit = require( './utils/can_emit_exit.js' ); var createExitHarness = require( './exit_harness.js' ); // VARIABLES // var harness; // MAIN // /** * Returns a benchmark harness. If a harness has already been created, returns the cached harness. * * @private * @param {Options} [options] - harness options * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @returns {Function} benchmark harness */ function getHarness( options, clbk ) { var opts; var cb; if ( harness ) { return harness; } if ( arguments.length > 1 ) { opts = options; cb = clbk; } else { opts = {}; cb = options; } opts.autoclose = !canEmitExit; harness = createExitHarness( opts, cb ); // Update state: getHarness.cached = true; return harness; } // EXPORTS // module.exports = getHarness; },{"./exit_harness.js":201,"./utils/can_emit_exit.js":220}],203:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); var Runner = require( './../runner' ); var nextTick = require( './../utils/next_tick.js' ); var DEFAULTS = require( './../defaults.json' ); var validate = require( './validate.js' ); var init = require( './init.js' ); // MAIN // /** * Creates a benchmark harness. * * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var bench = createHarness( onFinish ); * * function onFinish() { * bench.close(); * console.log( 'Exit code: %d', bench.exitCode ); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createHarness().createStream(); * stream.pipe( stdout ); */ function createHarness( options, clbk ) { var exitCode; var runner; var queue; var opts; var cb; opts = {}; if ( arguments.length === 1 ) { if ( isFunction( options ) ) { cb = options; } else if ( isObject( options ) ) { opts = options; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' ); } } else if ( arguments.length > 1 ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } cb = clbk; if ( !isFunction( cb ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' ); } } runner = new Runner(); if ( opts.autoclose ) { runner.once( 'done', close ); } if ( cb ) { runner.once( 'done', cb ); } exitCode = 0; queue = []; /** * Benchmark harness. * * @private * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @throws {Error} benchmark error * @returns {Function} benchmark harness */ function harness( name, options, benchmark ) { var opts; var err; var b; if ( !isString( name ) ) { throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' ); } opts = copy( DEFAULTS ); if ( arguments.length === 2 ) { if ( isFunction( options ) ) { b = options; } else { err = validate( opts, options ); if ( err ) { throw err; } } } else if ( arguments.length > 2 ) { err = validate( opts, options ); if ( err ) { throw err; } b = benchmark; if ( !isFunction( b ) ) { throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' ); } } // Add the benchmark to the initialization queue: queue.push( [ name, opts, b ] ); // Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)): if ( queue.length === 1 ) { nextTick( initialize ); } return harness; } /** * Initializes each benchmark. * * @private * @returns {void} */ function initialize() { var idx = -1; return next(); /** * Initialize the next benchmark. * * @private * @returns {void} */ function next() { var args; idx += 1; // If all benchmarks have been initialized, begin running the benchmarks: if ( idx === queue.length ) { queue.length = 0; return runner.run(); } // Initialize the next benchmark: args = queue[ idx ]; init( args[ 0 ], args[ 1 ], args[ 2 ], onInit ); } /** * Callback invoked after performing initialization tasks. * * @private * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @returns {void} */ function onInit( name, opts, benchmark ) { var b; var i; // Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state... for ( i = 0; i < opts.repeats; i++ ) { b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); runner.push( b ); } return next(); } } /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { exitCode = 1; } } /** * Returns a results stream. * * @private * @param {Object} [options] - options * @returns {TransformStream} transform stream */ function createStream( options ) { if ( arguments.length ) { return runner.createStream( options ); } return runner.createStream(); } /** * Closes a benchmark harness. * * @private */ function close() { runner.close(); } /** * Forcefully exits a benchmark harness. * * @private */ function exit() { runner.exit(); } /** * Returns the harness exit code. * * @private * @returns {NonNegativeInteger} exit code */ function getExitCode() { return exitCode; } setReadOnly( harness, 'createStream', createStream ); setReadOnly( harness, 'close', close ); setReadOnly( harness, 'exit', exit ); setReadOnlyAccessor( harness, 'exitCode', getExitCode ); return harness; } // EXPORTS // module.exports = createHarness; },{"./../benchmark-class":190,"./../defaults.json":200,"./../runner":217,"./../utils/next_tick.js":222,"./init.js":204,"./validate.js":207,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":334,"@stdlib/utils/define-nonenumerable-read-only-accessor":336,"@stdlib/utils/define-nonenumerable-read-only-property":338}],204:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var pretest = require( './pretest.js' ); var iterations = require( './iterations.js' ); // MAIN // /** * Performs benchmark initialization tasks. * * @private * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after completing initialization tasks * @returns {void} */ function init( name, opts, benchmark, clbk ) { // If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times... if ( !benchmark ) { opts.repeats = 1; return clbk( name, opts, benchmark ); } // If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark: if ( opts.skip ) { opts.repeats = 1; return clbk( name, opts, benchmark ); } // Perform pretests: pretest( name, opts, benchmark, onPreTest ); /** * Callback invoked upon completing pretests. * * @private * @param {Error} [error] - error object * @returns {void} */ function onPreTest( error ) { // If the pretests failed, don't run the benchmark multiple times... if ( error ) { opts.repeats = 1; opts.iterations = 1; return clbk( name, opts, benchmark ); } // If a user specified an iteration number, we can begin running benchmarks... if ( opts.iterations ) { return clbk( name, opts, benchmark ); } // Determine iteration number: iterations( name, opts, benchmark, onIterations ); } /** * Callback invoked upon determining an iteration number. * * @private * @param {(Error|null)} error - error object * @param {PositiveInteger} iter - number of iterations * @returns {void} */ function onIterations( error, iter ) { // If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times... if ( error ) { opts.repeats = 1; opts.iterations = 1; return clbk( name, opts, benchmark ); } opts.iterations = iter; return clbk( name, opts, benchmark ); } } // EXPORTS // module.exports = init; },{"./iterations.js":205,"./pretest.js":206}],205:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); // VARIABLES // var MIN_TIME = 0.1; // seconds var ITERATIONS = 10; // 10^1 var MAX_ITERATIONS = 10000000000; // 10^10 // MAIN // /** * Determines the number of iterations. * * @private * @param {string} name - benchmark name * @param {Options} options - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after determining number of iterations * @returns {void} */ function iterations( name, options, benchmark, clbk ) { var opts; var time; // Elapsed time (in seconds): time = 0; // Create a local copy: opts = copy( options ); opts.iterations = ITERATIONS; // Begin running benchmarks: return next(); /** * Run a new benchmark. * * @private */ function next() { var b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); b.once( 'end', onEnd ); b.run(); } /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && result.operator === 'result' ) { time = result.elapsed; } } /** * Callback invoked upon an `end` event. * * @private * @returns {void} */ function onEnd() { if ( time < MIN_TIME && opts.iterations < MAX_ITERATIONS ) { opts.iterations *= 10; return next(); } clbk( null, opts.iterations ); } } // EXPORTS // module.exports = iterations; },{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":334}],206:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); // MAIN // /** * Runs pretests to sanity check and/or catch failures. * * @private * @param {string} name - benchmark name * @param {Options} options - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after completing pretests */ function pretest( name, options, benchmark, clbk ) { var fail; var opts; var tic; var toc; var b; // Counters to determine the number of `tic` and `toc` events: tic = 0; toc = 0; // Local copy: opts = copy( options ); opts.iterations = 1; // Pretest to check for minimum requirements and/or errors... b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); b.on( 'tic', onTic ); b.on( 'toc', onToc ); b.once( 'end', onEnd ); b.run(); /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { fail = true; } } /** * Callback invoked upon a `tic` event. * * @private */ function onTic() { tic += 1; } /** * Callback invoked upon a `toc` event. * * @private */ function onToc() { toc += 1; } /** * Callback invoked upon an `end` event. * * @private * @returns {void} */ function onEnd() { var err; if ( fail ) { // Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices. err = new Error( 'benchmark failed' ); } else if ( tic !== 1 || toc !== 1 ) { // Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc). err = new Error( 'invalid benchmark' ); } if ( err ) { return clbk( err ); } return clbk(); } } // EXPORTS // module.exports = pretest; },{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":334}],207:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNull = require( '@stdlib/assert/is-null' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations] - number of iterations * @param {PositiveInteger} [options.repeats] - number of repeats * @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails * @returns {(Error|null)} error object or null * * @example * var opts = {}; * var options = { * 'skip': false, * 'iterations': 1e6, * 'repeats': 3, * 'timeout': 10000 * }; * * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'skip' ) ) { opts.skip = options.skip; if ( !isBoolean( opts.skip ) ) { return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' ); } } if ( hasOwnProp( options, 'iterations' ) ) { opts.iterations = options.iterations; if ( !isPositiveInteger( opts.iterations ) && !isNull( opts.iterations ) ) { return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' ); } } if ( hasOwnProp( options, 'repeats' ) ) { opts.repeats = options.repeats; if ( !isPositiveInteger( opts.repeats ) ) { return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' ); } } if ( hasOwnProp( options, 'timeout' ) ) { opts.timeout = options.timeout; if ( !isPositiveInteger( opts.timeout ) ) { return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],208:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Benchmark harness. * * @module @stdlib/bench/harness * * @example * var bench = require( '@stdlib/bench/harness' ); * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ // MODULES // var bench = require( './bench.js' ); // EXPORTS // module.exports = bench; },{"./bench.js":180}],209:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var fromCodePoint = require( '@stdlib/string/from-code-point' ); var log = require( './log.js' ); // MAIN // /** * Returns a Transform stream for logging to the console. * * @private * @returns {TransformStream} transform stream */ function createStream() { var stream; var line; stream = new TransformStream({ 'transform': transform, 'flush': flush }); line = ''; return stream; /** * Callback invoked upon receiving a new chunk. * * @private * @param {(Buffer|string)} chunk - chunk * @param {string} enc - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ function transform( chunk, enc, clbk ) { var c; var i; for ( i = 0; i < chunk.length; i++ ) { c = fromCodePoint( chunk[ i ] ); if ( c === '\n' ) { flush(); } else { line += c; } } clbk(); } /** * Callback to flush data to `stdout`. * * @private * @param {Callback} [clbk] - callback to invoke after processing data * @returns {void} */ function flush( clbk ) { try { log( line ); } catch ( err ) { stream.emit( 'error', err ); } line = ''; if ( clbk ) { return clbk(); } } } // EXPORTS // module.exports = createStream; },{"./log.js":210,"@stdlib/streams/node/transform":314,"@stdlib/string/from-code-point":318}],210:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Writes a string to the console. * * @private * @param {string} str - string to write */ function log( str ) { console.log( str ); // eslint-disable-line no-console } // EXPORTS // module.exports = log; },{}],211:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Removes any pending benchmarks. * * @private */ function clear() { /* eslint-disable no-invalid-this */ this._benchmarks.length = 0; } // EXPORTS // module.exports = clear; },{}],212:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Closes a benchmark runner. * * @private * @returns {void} */ function closeRunner() { /* eslint-disable no-invalid-this */ var self = this; if ( this._closed ) { return; } this._closed = true; if ( this._benchmarks.length ) { this.clear(); this._stream.write( '# WARNING: harness closed before completion.\n' ); } else { this._stream.write( '#\n' ); this._stream.write( '1..'+this.total+'\n' ); this._stream.write( '# total '+this.total+'\n' ); this._stream.write( '# pass '+this.pass+'\n' ); if ( this.fail ) { this._stream.write( '# fail '+this.fail+'\n' ); } if ( this.skip ) { this._stream.write( '# skip '+this.skip+'\n' ); } if ( this.todo ) { this._stream.write( '# todo '+this.todo+'\n' ); } if ( !this.fail ) { this._stream.write( '#\n# ok\n' ); } } this._stream.once( 'close', onClose ); this._stream.destroy(); /** * Callback invoked upon a `close` event. * * @private */ function onClose() { self.emit( 'close' ); } } // EXPORTS // module.exports = closeRunner; },{}],213:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable no-underscore-dangle */ 'use strict'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var nextTick = require( './../utils/next_tick.js' ); // VARIABLES // var TAP_HEADER = 'TAP version 13'; // MAIN // /** * Creates a results stream. * * @private * @param {Options} [options] - stream options * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream */ function createStream( options ) { /* eslint-disable no-invalid-this */ var stream; var opts; var self; var id; self = this; if ( arguments.length ) { opts = options; } else { opts = {}; } stream = new TransformStream( opts ); if ( opts.objectMode ) { id = 0; this.on( '_push', onPush ); this.on( 'done', onDone ); } else { stream.write( TAP_HEADER+'\n' ); this._stream.pipe( stream ); } this.on( '_run', onRun ); return stream; /** * Runs the next benchmark. * * @private */ function next() { nextTick( onTick ); } /** * Callback invoked upon the next tick. * * @private * @returns {void} */ function onTick() { var b = self._benchmarks.shift(); if ( b ) { b.run(); if ( !b.ended() ) { return b.once( 'end', next ); } return next(); } self._running = false; self.emit( 'done' ); } /** * Callback invoked upon a run event. * * @private * @returns {void} */ function onRun() { if ( !self._running ) { self._running = true; return next(); } } /** * Callback invoked upon a push event. * * @private * @param {Benchmark} b - benchmark */ function onPush( b ) { var bid = id; id += 1; b.once( 'prerun', onPreRun ); b.on( 'result', onResult ); b.on( 'end', onEnd ); /** * Callback invoked upon a `prerun` event. * * @private */ function onPreRun() { var row = { 'type': 'benchmark', 'name': b.name, 'id': bid }; stream.write( row ); } /** * Callback invoked upon a `result` event. * * @private * @param {(Object|string)} res - result */ function onResult( res ) { if ( isString( res ) ) { res = { 'benchmark': bid, 'type': 'comment', 'name': res }; } else if ( res.operator === 'result' ) { res.benchmark = bid; res.type = 'result'; } else { res.benchmark = bid; res.type = 'assert'; } stream.write( res ); } /** * Callback invoked upon an `end` event. * * @private */ function onEnd() { stream.write({ 'benchmark': bid, 'type': 'end' }); } } /** * Callback invoked upon a `done` event. * * @private */ function onDone() { stream.destroy(); } } // EXPORTS // module.exports = createStream; },{"./../utils/next_tick.js":222,"@stdlib/assert/is-string":158,"@stdlib/streams/node/transform":314}],214:[function(require,module,exports){ /* eslint-disable stdlib/jsdoc-require-throws-tags */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var replace = require( '@stdlib/string/replace' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var reEOL = require( '@stdlib/regexp/eol' ); // VARIABLES // var RE_WHITESPACE = /\s+/g; // MAIN // /** * Encodes an assertion. * * @private * @param {Object} result - result * @param {PositiveInteger} count - result count * @returns {string} encoded assertion */ function encodeAssertion( result, count ) { var actualStack; var errorStack; var expected; var actual; var indent; var stack; var lines; var out; var i; out = ''; if ( !result.ok ) { out += 'not '; } // Add result count: out += 'ok ' + count; // Add description: if ( result.name ) { out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' ); } // Append directives: if ( result.skip ) { out += ' # SKIP'; } else if ( result.todo ) { out += ' # TODO'; } out += '\n'; if ( result.ok ) { return out; } // Format diagnostics as YAML... indent = ' '; out += indent + '---\n'; out += indent + 'operator: ' + result.operator + '\n'; if ( hasOwnProp( result, 'actual' ) || hasOwnProp( result, 'expected' ) ) { // TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145) expected = result.expected; actual = result.actual; if ( actual !== actual && expected !== expected ) { throw new Error( 'TODO: remove me' ); } } if ( result.at ) { out += indent + 'at: ' + result.at + '\n'; } if ( result.actual ) { actualStack = result.actual.stack; } if ( result.error ) { errorStack = result.error.stack; } if ( actualStack ) { stack = actualStack; } else { stack = errorStack; } if ( stack ) { lines = stack.toString().split( reEOL.REGEXP ); out += indent + 'stack: |-\n'; for ( i = 0; i < lines.length; i++ ) { out += indent + ' ' + lines[ i ] + '\n'; } } out += indent + '...\n'; return out; } // EXPORTS // module.exports = encodeAssertion; },{"@stdlib/assert/has-own-property":53,"@stdlib/regexp/eol":298,"@stdlib/string/replace":320}],215:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // var YAML_INDENT = ' '; var YAML_BEGIN = YAML_INDENT + '---\n'; var YAML_END = YAML_INDENT + '...\n'; // MAIN // /** * Encodes a result as a YAML block. * * @private * @param {Object} result - result * @returns {string} encoded result */ function encodeResult( result ) { var out = YAML_BEGIN; out += YAML_INDENT + 'iterations: '+result.iterations+'\n'; out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n'; out += YAML_INDENT + 'rate: '+result.rate+'\n'; out += YAML_END; return out; } // EXPORTS // module.exports = encodeResult; },{}],216:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Forcefully exits a benchmark runner. * * @private */ function exit() { /* eslint-disable no-invalid-this */ var self; var i; for ( i = 0; i < this._benchmarks.length; i++ ) { this._benchmarks[ i ].exit(); } self = this; this.clear(); this._stream.once( 'close', onClose ); this._stream.destroy(); /** * Callback invoked upon a `close` event. * * @private */ function onClose() { self.emit( 'close' ); } } // EXPORTS // module.exports = exit; },{}],217:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var EventEmitter = require( 'events' ).EventEmitter; var inherit = require( '@stdlib/utils/inherit' ); var defineProperty = require( '@stdlib/utils/define-property' ); var TransformStream = require( '@stdlib/streams/node/transform' ); var push = require( './push.js' ); var createStream = require( './create_stream.js' ); var run = require( './run.js' ); var clear = require( './clear.js' ); var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare var exit = require( './exit.js' ); // MAIN // /** * Benchmark runner. * * @private * @constructor * @returns {Runner} Runner instance * * @example * var runner = new Runner(); */ function Runner() { if ( !( this instanceof Runner ) ) { return new Runner(); } EventEmitter.call( this ); // Private properties: defineProperty( this, '_benchmarks', { 'value': [], 'configurable': false, 'writable': false, 'enumerable': false }); defineProperty( this, '_stream', { 'value': new TransformStream(), 'configurable': false, 'writable': false, 'enumerable': false }); defineProperty( this, '_closed', { 'value': false, 'configurable': false, 'writable': true, 'enumerable': false }); defineProperty( this, '_running', { 'value': false, 'configurable': false, 'writable': true, 'enumerable': false }); // Public properties: defineProperty( this, 'total', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'fail', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'pass', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'skip', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'todo', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); return this; } /* * Inherit from the `EventEmitter` prototype. */ inherit( Runner, EventEmitter ); /** * Adds a new benchmark. * * @private * @memberof Runner.prototype * @function push * @param {Benchmark} b - benchmark */ defineProperty( Runner.prototype, 'push', { 'value': push, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Creates a results stream. * * @private * @memberof Runner.prototype * @function createStream * @param {Options} [options] - stream options * @returns {TransformStream} transform stream */ defineProperty( Runner.prototype, 'createStream', { 'value': createStream, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Runs pending benchmarks. * * @private * @memberof Runner.prototype * @function run */ defineProperty( Runner.prototype, 'run', { 'value': run, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Removes any pending benchmarks. * * @private * @memberof Runner.prototype * @function clear */ defineProperty( Runner.prototype, 'clear', { 'value': clear, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Closes a benchmark runner. * * @private * @memberof Runner.prototype * @function close */ defineProperty( Runner.prototype, 'close', { 'value': close, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Forcefully exits a benchmark runner. * * @private * @memberof Runner.prototype * @function exit */ defineProperty( Runner.prototype, 'exit', { 'value': exit, 'configurable': false, 'writable': false, 'enumerable': false }); // EXPORTS // module.exports = Runner; },{"./clear.js":211,"./close.js":212,"./create_stream.js":213,"./exit.js":216,"./push.js":218,"./run.js":219,"@stdlib/streams/node/transform":314,"@stdlib/utils/define-property":345,"@stdlib/utils/inherit":370,"events":423}],218:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable no-underscore-dangle */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var encodeAssertion = require( './encode_assertion.js' ); var encodeResult = require( './encode_result.js' ); // MAIN // /** * Adds a new benchmark. * * @private * @param {Benchmark} b - benchmark */ function push( b ) { /* eslint-disable no-invalid-this */ var self = this; this._benchmarks.push( b ); b.once( 'prerun', onPreRun ); b.on( 'result', onResult ); this.emit( '_push', b ); /** * Callback invoked upon a `prerun` event. * * @private */ function onPreRun() { self._stream.write( '# '+b.name+'\n' ); } /** * Callback invoked upon a `result` event. * * @private * @param {(Object|string)} res - result * @returns {void} */ function onResult( res ) { // Check for a comment... if ( isString( res ) ) { return self._stream.write( '# '+res+'\n' ); } if ( res.operator === 'result' ) { res = encodeResult( res ); return self._stream.write( res ); } self.total += 1; if ( res.ok ) { if ( res.skip ) { self.skip += 1; } else if ( res.todo ) { self.todo += 1; } self.pass += 1; } // According to the TAP spec, todos pass even if not "ok"... else if ( res.todo ) { self.pass += 1; self.todo += 1; } // Everything else is a failure... else { self.fail += 1; } res = encodeAssertion( res, self.total ); self._stream.write( res ); } } // EXPORTS // module.exports = push; },{"./encode_assertion.js":214,"./encode_result.js":215,"@stdlib/assert/is-string":158}],219:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Runs pending benchmarks. * * @private */ function run() { /* eslint-disable no-invalid-this */ this.emit( '_run' ); } // EXPORTS // module.exports = run; },{}],220:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var IS_BROWSER = require( '@stdlib/assert/is-browser' ); var canExit = require( './can_exit.js' ); // MAIN // var bool = ( !IS_BROWSER && canExit ); // EXPORTS // module.exports = bool; },{"./can_exit.js":221,"@stdlib/assert/is-browser":87}],221:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var proc = require( './process.js' ); // MAIN // var bool = ( proc && typeof proc.exit === 'function' ); // EXPORTS // module.exports = bool; },{"./process.js":223}],222:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Runs a function on a subsequent turn of the event loop. * * ## Notes * * - `process.nextTick` is only Node.js. * - `setImmediate` is non-standard. * - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc). * - Only API which is universal is `setTimeout`. * - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible. * * * @private * @param {Function} fcn - function to run upon a subsequent turn of the event loop */ function nextTick( fcn ) { setTimeout( fcn, 0 ); } // EXPORTS // module.exports = nextTick; },{}],223:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var proc = require( 'process' ); // EXPORTS // module.exports = proc; },{"process":434}],224:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Benchmark harness. * * @module @stdlib/bench * * @example * var bench = require( '@stdlib/bench' ); * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ // MODULES // var bench = require( '@stdlib/bench/harness' ); // EXPORTS // module.exports = bench; },{"@stdlib/bench/harness":208}],225:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * BLAS level 1 routine to copy values from `x` into `y`. * * @module @stdlib/blas/base/gcopy * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var gcopy = require( './main.js' ); var ndarray = require( './ndarray.js' ); // MAIN // setReadOnly( gcopy, 'ndarray', ndarray ); // EXPORTS // module.exports = gcopy; },{"./main.js":226,"./ndarray.js":227,"@stdlib/utils/define-nonenumerable-read-only-property":338}],226:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, y, strideY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ i ] = x[ i ]; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ i ] = x[ i ]; y[ i+1 ] = x[ i+1 ]; y[ i+2 ] = x[ i+2 ]; y[ i+3 ] = x[ i+3 ]; y[ i+4 ] = x[ i+4 ]; y[ i+5 ] = x[ i+5 ]; y[ i+6 ] = x[ i+6 ]; y[ i+7 ] = x[ i+7 ]; } return y; } if ( strideX < 0 ) { ix = (1-N) * strideX; } else { ix = 0; } if ( strideY < 0 ) { iy = (1-N) * strideY; } else { iy = 0; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],227:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NonNegativeInteger} offsetX - starting `x` index * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @param {NonNegativeInteger} offsetY - starting `y` index * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } ix = offsetX; iy = offsetY; // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ iy ] = x[ ix ]; y[ iy+1 ] = x[ ix+1 ]; y[ iy+2 ] = x[ ix+2 ]; y[ iy+3 ] = x[ ix+3 ]; y[ iy+4 ] = x[ ix+4 ]; y[ iy+5 ] = x[ ix+5 ]; y[ iy+6 ] = x[ ix+6 ]; y[ iy+7 ] = x[ ix+7 ]; ix += M; iy += M; } return y; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],228:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{"buffer":424}],229:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Buffer constructor. * * @module @stdlib/buffer/ctor * * @example * var ctor = require( '@stdlib/buffer/ctor' ); * * var b = new ctor( [ 1, 2, 3, 4 ] ); * // returns <Buffer> */ // MODULES // var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' ); var main = require( './buffer.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasNodeBufferSupport() ) { ctor = main; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./buffer.js":228,"./polyfill.js":230,"@stdlib/assert/has-node-buffer-support":51}],230:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: write (browser) polyfill // MAIN // /** * Buffer constructor. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],231:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // var bool = isFunction( Buffer.from ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":102,"@stdlib/buffer/ctor":229}],232:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Copy buffer data to a new `Buffer` instance. * * @module @stdlib/buffer/from-buffer * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * var copyBuffer = require( '@stdlib/buffer/from-buffer' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = copyBuffer( b1 ); * // returns <Buffer> */ // MODULES // var hasFrom = require( './has_from.js' ); var main = require( './main.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var copyBuffer; if ( hasFrom ) { copyBuffer = main; } else { copyBuffer = polyfill; } // EXPORTS // module.exports = copyBuffer; },{"./has_from.js":231,"./main.js":233,"./polyfill.js":234}],233:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return Buffer.from( buffer ); } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],234:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],235:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum length of a generic array. * * @module @stdlib/constants/array/max-array-length * * @example * var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' ); * // returns 4294967295 */ // MAIN // /** * Maximum length of a generic array. * * ```tex * 2^{32} - 1 * ``` * * @constant * @type {uinteger32} * @default 4294967295 */ var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation // EXPORTS // module.exports = MAX_ARRAY_LENGTH; },{}],236:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum length of a typed array. * * @module @stdlib/constants/array/max-typed-array-length * * @example * var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' ); * // returns 9007199254740991 */ // MAIN // /** * Maximum length of a typed array. * * ```tex * 2^{53} - 1 * ``` * * @constant * @type {number} * @default 9007199254740991 */ var MAX_TYPED_ARRAY_LENGTH = 9007199254740991; // EXPORTS // module.exports = MAX_TYPED_ARRAY_LENGTH; },{}],237:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * The bias of a double-precision floating-point number's exponent. * * @module @stdlib/constants/float64/exponent-bias * @type {integer32} * * @example * var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' ); * // returns 1023 */ // MAIN // /** * Bias of a double-precision floating-point number's exponent. * * ## Notes * * The bias can be computed via * * ```tex * \mathrm{bias} = 2^{k-1} - 1 * ``` * * where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\). * * @constant * @type {integer32} * @default 1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_EXPONENT_BIAS; },{}],238:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * High word mask for the exponent of a double-precision floating-point number. * * @module @stdlib/constants/float64/high-word-exponent-mask * @type {uinteger32} * * @example * var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); * // returns 2146435072 */ // MAIN // /** * High word mask for the exponent of a double-precision floating-point number. * * ## Notes * * The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence * * ```binarystring * 0 11111111111 00000000000000000000 * ``` * * @constant * @type {uinteger32} * @default 0x7ff00000 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000; // EXPORTS // module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK; },{}],239:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * High word mask for the significand of a double-precision floating-point number. * * @module @stdlib/constants/float64/high-word-significand-mask * @type {uinteger32} * * @example * var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); * // returns 1048575 */ // MAIN // /** * High word mask for the significand of a double-precision floating-point number. * * ## Notes * * The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence * * ```binarystring * 0 00000000000 11111111111111111111 * ``` * * @constant * @type {uinteger32} * @default 0x000fffff * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff; // EXPORTS // module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK; },{}],240:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum safe double-precision floating-point integer. * * @module @stdlib/constants/float64/max-safe-integer * @type {number} * * @example * var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); * // returns 9007199254740991 */ // MAIN // /** * Maximum safe double-precision floating-point integer. * * ## Notes * * The integer has the value * * ```tex * 2^{53} - 1 * ``` * * @constant * @type {number} * @default 9007199254740991 * @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html} * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991; // EXPORTS // module.exports = FLOAT64_MAX_SAFE_INTEGER; },{}],241:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Double-precision floating-point negative infinity. * * @module @stdlib/constants/float64/ninf * @type {number} * * @example * var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' ); * // returns -Infinity */ // MODULES // var Number = require( '@stdlib/number/ctor' ); // MAIN // /** * Double-precision floating-point negative infinity. * * ## Notes * * Double-precision floating-point negative infinity has the bit sequence * * ```binarystring * 1 11111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default Number.NEGATIVE_INFINITY * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_NINF = Number.NEGATIVE_INFINITY; // EXPORTS // module.exports = FLOAT64_NINF; },{"@stdlib/number/ctor":271}],242:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Double-precision floating-point positive infinity. * * @module @stdlib/constants/float64/pinf * @type {number} * * @example * var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' ); * // returns Infinity */ // MAIN // /** * Double-precision floating-point positive infinity. * * ## Notes * * Double-precision floating-point positive infinity has the bit sequence * * ```binarystring * 0 11111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default Number.POSITIVE_INFINITY * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = FLOAT64_PINF; },{}],243:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum signed 16-bit integer. * * @module @stdlib/constants/int16/max * @type {integer32} * * @example * var INT16_MAX = require( '@stdlib/constants/int16/max' ); * // returns 32767 */ // MAIN // /** * Maximum signed 16-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{15} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 0111111111111111 * ``` * * @constant * @type {integer32} * @default 32767 */ var INT16_MAX = 32767|0; // asm type annotation // EXPORTS // module.exports = INT16_MAX; },{}],244:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Minimum signed 16-bit integer. * * @module @stdlib/constants/int16/min * @type {integer32} * * @example * var INT16_MIN = require( '@stdlib/constants/int16/min' ); * // returns -32768 */ // MAIN // /** * Minimum signed 16-bit integer. * * ## Notes * * The number has the value * * ```tex * -(2^{15}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 1000000000000000 * ``` * * @constant * @type {integer32} * @default -32768 */ var INT16_MIN = -32768|0; // asm type annotation // EXPORTS // module.exports = INT16_MIN; },{}],245:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum signed 32-bit integer. * * @module @stdlib/constants/int32/max * @type {integer32} * * @example * var INT32_MAX = require( '@stdlib/constants/int32/max' ); * // returns 2147483647 */ // MAIN // /** * Maximum signed 32-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{31} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 01111111111111111111111111111111 * ``` * * @constant * @type {integer32} * @default 2147483647 */ var INT32_MAX = 2147483647|0; // asm type annotation // EXPORTS // module.exports = INT32_MAX; },{}],246:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Minimum signed 32-bit integer. * * @module @stdlib/constants/int32/min * @type {integer32} * * @example * var INT32_MIN = require( '@stdlib/constants/int32/min' ); * // returns -2147483648 */ // MAIN // /** * Minimum signed 32-bit integer. * * ## Notes * * The number has the value * * ```tex * -(2^{31}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 10000000000000000000000000000000 * ``` * * @constant * @type {integer32} * @default -2147483648 */ var INT32_MIN = -2147483648|0; // asm type annotation // EXPORTS // module.exports = INT32_MIN; },{}],247:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum signed 8-bit integer. * * @module @stdlib/constants/int8/max * @type {integer32} * * @example * var INT8_MAX = require( '@stdlib/constants/int8/max' ); * // returns 127 */ // MAIN // /** * Maximum signed 8-bit integer. * * ## Notes * * The number is given by * * ```tex * 2^{7} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 01111111 * ``` * * @constant * @type {integer32} * @default 127 */ var INT8_MAX = 127|0; // asm type annotation // EXPORTS // module.exports = INT8_MAX; },{}],248:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Minimum signed 8-bit integer. * * @module @stdlib/constants/int8/min * @type {integer32} * * @example * var INT8_MIN = require( '@stdlib/constants/int8/min' ); * // returns -128 */ // MAIN // /** * Minimum signed 8-bit integer. * * ## Notes * * The number is given by * * ```tex * -(2^{7}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 10000000 * ``` * * @constant * @type {integer32} * @default -128 */ var INT8_MIN = -128|0; // asm type annotation // EXPORTS // module.exports = INT8_MIN; },{}],249:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum unsigned 16-bit integer. * * @module @stdlib/constants/uint16/max * @type {integer32} * * @example * var UINT16_MAX = require( '@stdlib/constants/uint16/max' ); * // returns 65535 */ // MAIN // /** * Maximum unsigned 16-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{16} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 1111111111111111 * ``` * * @constant * @type {integer32} * @default 65535 */ var UINT16_MAX = 65535|0; // asm type annotation // EXPORTS // module.exports = UINT16_MAX; },{}],250:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum unsigned 32-bit integer. * * @module @stdlib/constants/uint32/max * @type {uinteger32} * * @example * var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); * // returns 4294967295 */ // MAIN // /** * Maximum unsigned 32-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{32} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 11111111111111111111111111111111 * ``` * * @constant * @type {uinteger32} * @default 4294967295 */ var UINT32_MAX = 4294967295; // EXPORTS // module.exports = UINT32_MAX; },{}],251:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum unsigned 8-bit integer. * * @module @stdlib/constants/uint8/max * @type {integer32} * * @example * var UINT8_MAX = require( '@stdlib/constants/uint8/max' ); * // returns 255 */ // MAIN // /** * Maximum unsigned 8-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{8} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 11111111 * ``` * * @constant * @type {integer32} * @default 255 */ var UINT8_MAX = 255|0; // asm type annotation // EXPORTS // module.exports = UINT8_MAX; },{}],252:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum Unicode code point in the Basic Multilingual Plane (BMP). * * @module @stdlib/constants/unicode/max-bmp * @type {integer32} * * @example * var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' ); * // returns 65535 */ // MAIN // /** * Maximum Unicode code point in the Basic Multilingual Plane (BMP). * * @constant * @type {integer32} * @default 65535 * @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode} */ var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation // EXPORTS // module.exports = UNICODE_MAX_BMP; },{}],253:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Maximum Unicode code point. * * @module @stdlib/constants/unicode/max * @type {integer32} * * @example * var UNICODE_MAX = require( '@stdlib/constants/unicode/max' ); * // returns 1114111 */ // MAIN // /** * Maximum Unicode code point. * * @constant * @type {integer32} * @default 1114111 * @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode} */ var UNICODE_MAX = 0x10FFFF|0; // asm type annotation // EXPORTS // module.exports = UNICODE_MAX; },{}],254:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a finite double-precision floating-point number is an integer. * * @module @stdlib/math/base/assert/is-integer * * @example * var isInteger = require( '@stdlib/math/base/assert/is-integer' ); * * var bool = isInteger( 1.0 ); * // returns true * * bool = isInteger( 3.14 ); * // returns false */ // MODULES // var isInteger = require( './is_integer.js' ); // EXPORTS // module.exports = isInteger; },{"./is_integer.js":255}],255:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var floor = require( '@stdlib/math/base/special/floor' ); // MAIN // /** * Tests if a finite double-precision floating-point number is an integer. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is an integer * * @example * var bool = isInteger( 1.0 ); * // returns true * * @example * var bool = isInteger( 3.14 ); * // returns false */ function isInteger( x ) { return (floor(x) === x); } // EXPORTS // module.exports = isInteger; },{"@stdlib/math/base/special/floor":260}],256:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a double-precision floating-point numeric value is `NaN`. * * @module @stdlib/math/base/assert/is-nan * * @example * var isnan = require( '@stdlib/math/base/assert/is-nan' ); * * var bool = isnan( NaN ); * // returns true * * bool = isnan( 7.0 ); * // returns false */ // MODULES // var isnan = require( './main.js' ); // EXPORTS // module.exports = isnan; },{"./main.js":257}],257:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests if a double-precision floating-point numeric value is `NaN`. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is `NaN` * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( 7.0 ); * // returns false */ function isnan( x ) { return ( x !== x ); } // EXPORTS // module.exports = isnan; },{}],258:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Test if a double-precision floating-point numeric value is positive zero. * * @module @stdlib/math/base/assert/is-positive-zero * * @example * var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); * * var bool = isPositiveZero( 0.0 ); * // returns true * * bool = isPositiveZero( -0.0 ); * // returns false */ // MODULES // var isPositiveZero = require( './main.js' ); // EXPORTS // module.exports = isPositiveZero; },{"./main.js":259}],259:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is positive zero. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is positive zero * * @example * var bool = isPositiveZero( 0.0 ); * // returns true * * @example * var bool = isPositiveZero( -0.0 ); * // returns false */ function isPositiveZero( x ) { return (x === 0.0 && 1.0/x === PINF); } // EXPORTS // module.exports = isPositiveZero; },{"@stdlib/constants/float64/pinf":242}],260:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Round a double-precision floating-point number toward negative infinity. * * @module @stdlib/math/base/special/floor * * @example * var floor = require( '@stdlib/math/base/special/floor' ); * * var v = floor( -4.2 ); * // returns -5.0 * * v = floor( 9.99999 ); * // returns 9.0 * * v = floor( 0.0 ); * // returns 0.0 * * v = floor( NaN ); * // returns NaN */ // MODULES // var floor = require( './main.js' ); // EXPORTS // module.exports = floor; },{"./main.js":261}],261:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: implementation (?) /** * Rounds a double-precision floating-point number toward negative infinity. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = floor( -4.2 ); * // returns -5.0 * * @example * var v = floor( 9.99999 ); * // returns 9.0 * * @example * var v = floor( 0.0 ); * // returns 0.0 * * @example * var v = floor( NaN ); * // returns NaN */ var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = floor; },{}],262:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return the maximum value. * * @module @stdlib/math/base/special/max * * @example * var max = require( '@stdlib/math/base/special/max' ); * * var v = max( 3.14, 4.2 ); * // returns 4.2 * * v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * v = max( 3.14, NaN ); * // returns NaN * * v = max( +0.0, -0.0 ); * // returns +0.0 */ // MODULES // var max = require( './max.js' ); // EXPORTS // module.exports = max; },{"./max.js":263}],263:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Returns the maximum value. * * @param {number} [x] - first number * @param {number} [y] - second number * @param {...number} [args] - numbers * @returns {number} maximum value * * @example * var v = max( 3.14, 4.2 ); * // returns 4.2 * * @example * var v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * @example * var v = max( 3.14, NaN ); * // returns NaN * * @example * var v = max( +0.0, -0.0 ); * // returns +0.0 */ function max( x, y ) { var len; var m; var v; var i; len = arguments.length; if ( len === 2 ) { if ( isnan( x ) || isnan( y ) ) { return NaN; } if ( x === PINF || y === PINF ) { return PINF; } if ( x === y && x === 0.0 ) { if ( isPositiveZero( x ) ) { return x; } return y; } if ( x > y ) { return x; } return y; } m = NINF; for ( i = 0; i < len; i++ ) { v = arguments[ i ]; if ( isnan( v ) || v === PINF ) { return v; } if ( v > m ) { m = v; } else if ( v === m && v === 0.0 && isPositiveZero( v ) ) { m = v; } } return m; } // EXPORTS // module.exports = max; },{"@stdlib/constants/float64/ninf":241,"@stdlib/constants/float64/pinf":242,"@stdlib/math/base/assert/is-nan":256,"@stdlib/math/base/assert/is-positive-zero":258}],264:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Decompose a double-precision floating-point number into integral and fractional parts. * * @module @stdlib/math/base/special/modf * * @example * var modf = require( '@stdlib/math/base/special/modf' ); * * var parts = modf( 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var modf = require( '@stdlib/math/base/special/modf' ); * * var out = new Float64Array( 2 ); * * var parts = modf( out, 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * var bool = ( parts === out ); * // returns true */ // MODULES // var modf = require( './main.js' ); // EXPORTS // module.exports = modf; },{"./main.js":265}],265:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var fcn = require( './modf.js' ); // MAIN // /** * Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value. * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var parts = modf( 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var out = new Float64Array( 2 ); * * var parts = modf( out, 3.14 ); * // returns <Float64Array>[ 3.0, 0.14000000000000012 ] * * var bool = ( parts === out ); * // returns true */ function modf( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0.0, 0.0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = modf; },{"./modf.js":266}],266:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var toWords = require( '@stdlib/number/float64/base/to-words' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' ); var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length // VARIABLES // // 4294967295 => 0xffffffff => 11111111111111111111111111111111 var ALL_ONES = 4294967295>>>0; // asm type annotation // High/low words workspace: var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe // MAIN // /** * Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value. * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var parts = modf( [ 0.0, 0.0 ], 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] */ function modf( out, x ) { var high; var low; var exp; var i; // Special cases... if ( x < 1.0 ) { if ( x < 0.0 ) { modf( out, -x ); out[ 0 ] *= -1.0; out[ 1 ] *= -1.0; return out; } if ( x === 0.0 ) { // [ +-0, +-0 ] out[ 0 ] = x; out[ 1 ] = x; return out; } out[ 0 ] = 0.0; out[ 1 ] = x; return out; } if ( isnan( x ) ) { out[ 0 ] = NaN; out[ 1 ] = NaN; return out; } if ( x === PINF ) { out[ 0 ] = PINF; out[ 1 ] = 0.0; return out; } // Decompose |x|... // Extract the high and low words: toWords( WORDS, x ); high = WORDS[ 0 ]; low = WORDS[ 1 ]; // Extract the unbiased exponent from the high word: exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation // Handle smaller values (x < 2**20 = 1048576)... if ( exp < 20 ) { i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation // Determine if `x` is integral by checking for significand bits which cannot be exponentiated away... if ( ((high&i)|low) === 0 ) { out[ 0 ] = x; out[ 1 ] = 0.0; return out; } // Turn off all the bits which cannot be exponentiated away: high &= (~i); // Generate the integral part: i = fromWords( high, 0 ); // The fractional part is whatever is leftover: out[ 0 ] = i; out[ 1 ] = x - i; return out; } // Check if `x` can even have a fractional part... if ( exp > 51 ) { // `x` is integral: out[ 0 ] = x; out[ 1 ] = 0.0; return out; } i = ALL_ONES >>> (exp-20); // Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away... if ( (low&i) === 0 ) { out[ 0 ] = x; out[ 1 ] = 0.0; return out; } // Turn off all the bits which cannot be exponentiated away: low &= (~i); // Generate the integral part: i = fromWords( high, low ); // The fractional part is whatever is leftover: out[ 0 ] = i; out[ 1 ] = x - i; return out; } // EXPORTS // module.exports = modf; },{"@stdlib/constants/float64/exponent-bias":237,"@stdlib/constants/float64/high-word-exponent-mask":238,"@stdlib/constants/float64/high-word-significand-mask":239,"@stdlib/constants/float64/pinf":242,"@stdlib/math/base/assert/is-nan":256,"@stdlib/number/float64/base/from-words":273,"@stdlib/number/float64/base/to-words":276}],267:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: implementation /** * Round a numeric value to the nearest integer. * * @module @stdlib/math/base/special/round * * @example * var round = require( '@stdlib/math/base/special/round' ); * * var v = round( -4.2 ); * // returns -4.0 * * v = round( -4.5 ); * // returns -4.0 * * v = round( -4.6 ); * // returns -5.0 * * v = round( 9.99999 ); * // returns 10.0 * * v = round( 9.5 ); * // returns 10.0 * * v = round( 9.2 ); * // returns 9.0 * * v = round( 0.0 ); * // returns 0.0 * * v = round( -0.0 ); * // returns -0.0 * * v = round( Infinity ); * // returns Infinity * * v = round( -Infinity ); * // returns -Infinity * * v = round( NaN ); * // returns NaN */ // MODULES // var round = require( './round.js' ); // EXPORTS // module.exports = round; },{"./round.js":268}],268:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // TODO: implementation /** * Rounds a numeric value to the nearest integer. * * @param {number} x - input value * @returns {number} function value * * @example * var v = round( -4.2 ); * // returns -4.0 * * @example * var v = round( -4.5 ); * // returns -4.0 * * @example * var v = round( -4.6 ); * // returns -5.0 * * @example * var v = round( 9.99999 ); * // returns 10.0 * * @example * var v = round( 9.5 ); * // returns 10.0 * * @example * var v = round( 9.2 ); * // returns 9.0 * * @example * var v = round( 0.0 ); * // returns 0.0 * * @example * var v = round( -0.0 ); * // returns -0.0 * * @example * var v = round( Infinity ); * // returns Infinity * * @example * var v = round( -Infinity ); * // returns -Infinity * * @example * var v = round( NaN ); * // returns NaN */ var round = Math.round; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = round; },{}],269:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Perform C-like multiplication of two unsigned 32-bit integers. * * @module @stdlib/math/base/special/uimul * * @example * var uimul = require( '@stdlib/math/base/special/uimul' ); * * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ // MODULES // var uimul = require( './main.js' ); // EXPORTS // module.exports = uimul; },{"./main.js":270}],270:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // // Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111 var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation // MAIN // /** * Performs C-like multiplication of two unsigned 32-bit integers. * * ## Method * * - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words * * ```tex * a = w_h*2^{16} + w_l * ``` * * where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) * * ```binarystring * 11111111111111111111111111111111 * ``` * * The 16-bit high word is then * * ```binarystring * 1111111111111111 * ``` * * and the 16-bit low word * * ```binarystring * 1111111111111111 * ``` * * If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is * * ```binarystring * 11111111111111110000000000000000 * ``` * * Similarly, upon casting the low word to 32-bit precision, the bit sequence is * * ```binarystring * 00000000000000001111111111111111 * ``` * * From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\). * * - Accordingly, the multiplication of two 32-bit integers can be expressed * * ```tex * \begin{align*} * a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\ * &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\ * &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} * \end{align*} * ``` * * - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits. * * - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result. * * - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder. * * ```tex * a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16 * ``` * * - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words. * * * @param {uinteger32} a - integer * @param {uinteger32} b - integer * @returns {uinteger32} product * * @example * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ function uimul( a, b ) { var lbits; var mbits; var ha; var hb; var la; var lb; a >>>= 0; // asm type annotation b >>>= 0; // asm type annotation // Isolate the most significant 16-bits: ha = ( a>>>16 )>>>0; // asm type annotation hb = ( b>>>16 )>>>0; // asm type annotation // Isolate the least significant 16-bits: la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation // Compute partial sums: lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow // The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum): return ( lbits + mbits )>>>0; // asm type annotation } // EXPORTS // module.exports = uimul; },{}],271:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Constructor which returns a `Number` object. * * @module @stdlib/number/ctor * * @example * var Number = require( '@stdlib/number/ctor' ); * * var v = new Number( 10.0 ); * // returns <Number> */ // MODULES // var Number = require( './number.js' ); // EXPORTS // module.exports = Number; },{"./number.js":272}],272:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // EXPORTS // module.exports = Number; // eslint-disable-line stdlib/require-globals },{}],273:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @module @stdlib/number/float64/base/from-words * * @example * var fromWords = require( '@stdlib/number/float64/base/from-words' ); * * var v = fromWords( 1774486211, 2479577218 ); * // returns 3.14e201 * * v = fromWords( 3221823995, 1413754136 ); * // returns -3.141592653589793 * * v = fromWords( 0, 0 ); * // returns 0.0 * * v = fromWords( 2147483648, 0 ); * // returns -0.0 * * v = fromWords( 2146959360, 0 ); * // returns NaN * * v = fromWords( 2146435072, 0 ); * // returns Infinity * * v = fromWords( 4293918720, 0 ); * // returns -Infinity */ // MODULES // var fromWords = require( './main.js' ); // EXPORTS // module.exports = fromWords; },{"./main.js":275}],274:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isLittleEndian = require( '@stdlib/assert/is-little-endian' ); // MAIN // var indices; var HIGH; var LOW; if ( isLittleEndian === true ) { HIGH = 1; // second index LOW = 0; // first index } else { HIGH = 0; // first index LOW = 1; // second index } indices = { 'HIGH': HIGH, 'LOW': LOW }; // EXPORTS // module.exports = indices; },{"@stdlib/assert/is-little-endian":116}],275:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Uint32Array = require( '@stdlib/array/uint32' ); var Float64Array = require( '@stdlib/array/float64' ); var indices = require( './indices.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); var HIGH = indices.HIGH; var LOW = indices.LOW; // MAIN // /** * Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * ## Notes * * ```text * float64 (64 bits) * f := fraction (significand/mantissa) (52 bits) * e := exponent (11 bits) * s := sign bit (1 bit) * * |-------- -------- -------- -------- -------- -------- -------- --------| * | Float64 | * |-------- -------- -------- -------- -------- -------- -------- --------| * | Uint32 | Uint32 | * |-------- -------- -------- -------- -------- -------- -------- --------| * ``` * * If little endian (more significant bits last): * * ```text * <-- lower higher --> * | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 | * ``` * * If big endian (more significant bits first): * * ```text * <-- higher lower --> * |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 | * ``` * * * In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first. * * * ## References * * - [Open Group][1] * * [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm * * @param {uinteger32} high - higher order word (unsigned 32-bit integer) * @param {uinteger32} low - lower order word (unsigned 32-bit integer) * @returns {number} floating-point number * * @example * var v = fromWords( 1774486211, 2479577218 ); * // returns 3.14e201 * * @example * var v = fromWords( 3221823995, 1413754136 ); * // returns -3.141592653589793 * * @example * var v = fromWords( 0, 0 ); * // returns 0.0 * * @example * var v = fromWords( 2147483648, 0 ); * // returns -0.0 * * @example * var v = fromWords( 2146959360, 0 ); * // returns NaN * * @example * var v = fromWords( 2146435072, 0 ); * // returns Infinity * * @example * var v = fromWords( 4293918720, 0 ); * // returns -Infinity */ function fromWords( high, low ) { UINT32_VIEW[ HIGH ] = high; UINT32_VIEW[ LOW ] = low; return FLOAT64_VIEW[ 0 ]; } // EXPORTS // module.exports = fromWords; },{"./indices.js":274,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],276:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @module @stdlib/number/float64/base/to-words * * @example * var toWords = require( '@stdlib/number/float64/base/to-words' ); * * var w = toWords( 3.14e201 ); * // returns [ 1774486211, 2479577218 ] * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * var toWords = require( '@stdlib/number/float64/base/to-words' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ // MODULES // var toWords = require( './main.js' ); // EXPORTS // module.exports = toWords; },{"./main.js":278}],277:[function(require,module,exports){ arguments[4][274][0].apply(exports,arguments) },{"@stdlib/assert/is-little-endian":116,"dup":274}],278:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var fcn = require( './to_words.js' ); // MAIN // /** * Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var w = toWords( 3.14e201 ); * // returns [ 1774486211, 2479577218 ] * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ function toWords( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0, 0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = toWords; },{"./to_words.js":279}],279:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Uint32Array = require( '@stdlib/array/uint32' ); var Float64Array = require( '@stdlib/array/float64' ); var indices = require( './indices.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); var HIGH = indices.HIGH; var LOW = indices.LOW; // MAIN // /** * Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * ## Notes * * ```text * float64 (64 bits) * f := fraction (significand/mantissa) (52 bits) * e := exponent (11 bits) * s := sign bit (1 bit) * * |-------- -------- -------- -------- -------- -------- -------- --------| * | Float64 | * |-------- -------- -------- -------- -------- -------- -------- --------| * | Uint32 | Uint32 | * |-------- -------- -------- -------- -------- -------- -------- --------| * ``` * * If little endian (more significant bits last): * * ```text * <-- lower higher --> * | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 | * ``` * * If big endian (more significant bits first): * * ```text * <-- higher lower --> * |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 | * ``` * * In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first. * * * ## References * * - [Open Group][1] * * [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm * * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ function toWords( out, x ) { FLOAT64_VIEW[ 0 ] = x; out[ 0 ] = UINT32_VIEW[ HIGH ]; out[ 1 ] = UINT32_VIEW[ LOW ]; return out; } // EXPORTS // module.exports = toWords; },{"./indices.js":277,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],280:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); // VARIABLES // var NUM_WARMUPS = 8; // MAIN // /** * Initializes a shuffle table. * * @private * @param {PRNG} rand - pseudorandom number generator * @param {Int32Array} table - table * @param {PositiveInteger} N - table size * @throws {Error} PRNG returned `NaN` * @returns {NumberArray} shuffle table */ function createTable( rand, table, N ) { var v; var i; // "warm-up" the PRNG... for ( i = 0; i < NUM_WARMUPS; i++ ) { v = rand(); // Prevent the above loop from being discarded by the compiler... if ( isnan( v ) ) { throw new Error( 'unexpected error. PRNG returned `NaN`.' ); } } // Initialize the shuffle table... for ( i = N-1; i >= 0; i-- ) { table[ i ] = rand(); } return table; } // EXPORTS // module.exports = createTable; },{"@stdlib/math/base/assert/is-nan":256}],281:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var floor = require( '@stdlib/math/base/special/floor' ); var Int32Array = require( '@stdlib/array/int32' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var typedarray2json = require( '@stdlib/array/to-json' ); var createTable = require( './create_table.js' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the number of elements in the shuffle table: var TABLE_LENGTH = 32; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // table, other, seed // Define the index offset of the "table" section in the state array: var TABLE_SECTION_OFFSET = 2; // | version | num_sections | table_length | ...table | other_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = TABLE_LENGTH + 3; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = TABLE_LENGTH + 6; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = TABLE_LENGTH + 7; // 1 (version) + 1 (num_sections) + 1 (table_length) + TABLE_LENGTH (table) + 1 (state_length) + 1 (shuffle_state) + 1 (prng_state) + 1 (seed_length) // Define the indices for the shuffle table and PRNG states: var SHUFFLE_STATE = STATE_SECTION_OFFSET + 1; var PRNG_STATE = STATE_SECTION_OFFSET + 2; // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "table" section must equal `TABLE_LENGTH`... if ( state[ TABLE_SECTION_OFFSET ] !== TABLE_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible table length. Expected: '+TABLE_LENGTH+'. Actual: '+state[ TABLE_SECTION_OFFSET ]+'.' ); } // The length of the "state" section must equal `2`... if ( state[ STATE_SECTION_OFFSET ] !== 2 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(2).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} shuffled LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed[ 0 ]; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } setReadOnly( minstdShuffle, 'NAME', 'minstd-shuffle' ); setReadOnlyAccessor( minstdShuffle, 'seed', getSeed ); setReadOnlyAccessor( minstdShuffle, 'seedLength', getSeedLength ); setReadWriteAccessor( minstdShuffle, 'state', getState, setState ); setReadOnlyAccessor( minstdShuffle, 'stateLength', getStateLength ); setReadOnlyAccessor( minstdShuffle, 'byteLength', getStateSize ); setReadOnly( minstdShuffle, 'toJSON', toJSON ); setReadOnly( minstdShuffle, 'MIN', 1 ); setReadOnly( minstdShuffle, 'MAX', INT32_MAX-1 ); setReadOnly( minstdShuffle, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstdShuffle.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstdShuffle.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstdShuffle.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstdShuffle; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. shuffle table * 2. internal PRNG state * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstdShuffle.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = STATE[ PRNG_STATE ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation STATE[ PRNG_STATE ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ function minstdShuffle() { var s; var i; s = STATE[ SHUFFLE_STATE ]; i = floor( TABLE_LENGTH * (s/INT32_MAX) ); // Pull a state from the table: s = state[ i ]; // Update the PRNG state: STATE[ SHUFFLE_STATE ] = s; // Replace the pulled state: state[ i ] = minstd(); return s; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = normalized(); * // returns <number> */ function normalized() { return (minstdShuffle()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./create_table.js":280,"./rand_int32.js":284,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":245,"@stdlib/math/base/special/floor":260,"@stdlib/utils/define-nonenumerable-read-only-accessor":336,"@stdlib/utils/define-nonenumerable-read-only-property":338,"@stdlib/utils/define-nonenumerable-read-write-accessor":340}],282:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * A linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @module @stdlib/random/base/minstd-shuffle * * @example * var minstd = require( '@stdlib/random/base/minstd-shuffle' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd-shuffle' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":281,"./main.js":283,"@stdlib/utils/define-nonenumerable-read-only-property":338}],283:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * This implementation subsequently shuffles the output of a linear congruential pseudorandom number generator (LCG) using a shuffle table in accordance with the Bays-Durham algorithm. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Bays, Carter, and S. D. Durham. 1976. "Improving a Poor Random Number Generator." _ACM Transactions on Mathematical Software_ 2 (1). New York, NY, USA: ACM: 59–64. doi:[10.1145/355666.355670](http://dx.doi.org/10.1145/355666.355670). * - Herzog, T.N., and G. Lord. 2002. _Applications of Monte Carlo Methods to Finance and Insurance_. ACTEX Publications. [https://books.google.com/books?id=vC7I\\\_gdX-A0C](https://books.google.com/books?id=vC7I\_gdX-A0C). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":281,"./rand_int32.js":284}],284:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var INT32_MAX = require( '@stdlib/constants/int32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = INT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{31}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randint32(); * // returns <number> */ function randint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v|0; // asm type annotation } // EXPORTS // module.exports = randint32; },{"@stdlib/constants/int32/max":245,"@stdlib/math/base/special/floor":260}],285:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var Int32Array = require( '@stdlib/array/int32' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 2; // state, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = 4; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = 5; // 1 (version) + 1 (num_sections) + 1 (state_length) + 1 (state) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `1`... if ( state[ STATE_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(1).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } setReadOnly( minstd, 'NAME', 'minstd' ); setReadOnlyAccessor( minstd, 'seed', getSeed ); setReadOnlyAccessor( minstd, 'seedLength', getSeedLength ); setReadWriteAccessor( minstd, 'state', getState, setState ); setReadOnlyAccessor( minstd, 'stateLength', getStateLength ); setReadOnlyAccessor( minstd, 'byteLength', getStateSize ); setReadOnly( minstd, 'toJSON', toJSON ); setReadOnly( minstd, 'MIN', 1 ); setReadOnly( minstd, 'MAX', INT32_MAX-1 ); setReadOnly( minstd, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstd.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstd.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstd.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstd; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `2` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `2`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstd.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = state[ 0 ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation state[ 0 ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number */ function normalized() { return (minstd()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_int32.js":288,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":245,"@stdlib/utils/define-nonenumerable-read-only-accessor":336,"@stdlib/utils/define-nonenumerable-read-only-property":338,"@stdlib/utils/define-nonenumerable-read-write-accessor":340}],286:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * A linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @module @stdlib/random/base/minstd * * @example * var minstd = require( '@stdlib/random/base/minstd' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":285,"./main.js":287,"@stdlib/utils/define-nonenumerable-read-only-property":338}],287:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Park, S. K., and K. W. Miller. 1988. "Random Number Generators: Good Ones Are Hard to Find." _Communications of the ACM_ 31 (10). New York, NY, USA: ACM: 1192–1201. doi:[10.1145/63039.63042](http://dx.doi.org/10.1145/63039.63042). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":285,"./rand_int32.js":288}],288:[function(require,module,exports){ arguments[4][284][0].apply(exports,arguments) },{"@stdlib/constants/int32/max":245,"@stdlib/math/base/special/floor":260,"dup":284}],289:[function(require,module,exports){ /* eslint-disable max-lines, max-len */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. * * * ## Notice * * The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript. * * ```text * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * 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 OWNER 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. * ``` */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var Uint32Array = require( '@stdlib/array/uint32' ); var max = require( '@stdlib/math/base/special/max' ); var uimul = require( '@stdlib/math/base/special/uimul' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randuint32 = require( './rand_uint32.js' ); // VARIABLES // // Define the size of the state array (see refs): var N = 624; // Define a (magic) constant used for indexing into the state array: var M = 397; // Define the maximum seed: 11111111111111111111111111111111 var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation // For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010 var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation // Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000 var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation // Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111 var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation // Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101 var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation // Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101 var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation // Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101 var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation // Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000 var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation // Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000 var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation // Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111 var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation // MAG01[x] = x * MATRIX_A; for x = {0,1} var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation // Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992 var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length // 2^26: 67108864 var TWO_26 = 67108864 >>> 0; // asm type annotation // 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000 var TWO_32 = 0x80000000 >>> 0; // asm type annotation // 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001 var ONE = 0x1 >>> 0; // asm type annotation // Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53 var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // state, other, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the "other" section in the state array: var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Uint32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `N`... if ( state[ STATE_SECTION_OFFSET ] !== N ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "other" section must equal `1`... if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } /** * Returns an initial PRNG state. * * @private * @param {Uint32Array} state - state array * @param {PositiveInteger} N - state size * @param {uinteger32} s - seed * @returns {Uint32Array} state array */ function createState( state, N, s ) { var i; // Set the first element of the state array to the provided seed: state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation // Initialize the remaining state array elements: for ( i = 1; i < N; i++ ) { /* * In the original C implementation (see `init_genrand()`), * * ```c * mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i) * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation } return state; } /** * Initializes a PRNG state array according to a seed array. * * @private * @param {Uint32Array} state - state array * @param {NonNegativeInteger} N - state array length * @param {Collection} seed - seed array * @param {NonNegativeInteger} M - seed array length * @returns {Uint32Array} state array */ function initState( state, N, seed, M ) { var s; var i; var j; var k; i = 1; j = 0; for ( k = max( N, M ); k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation i += 1; j += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } if ( j >= M ) { j = 0; } } for ( k = N-1; k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation i += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } } // Ensure a non-zero initial state array: state[ 0 ] = TWO_32; // MSB (most significant bit) is 1 return state; } /** * Updates a PRNG's internal state by generating the next `N` words. * * @private * @param {Uint32Array} state - state array * @returns {Uint32Array} state array */ function twist( state ) { var w; var i; var j; var k; k = N - M; for ( i = 0; i < k; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } j = N - 1; for ( ; i < j; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK ); state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; return state; } // MAIN // /** * Returns a 32-bit Mersenne Twister pseudorandom number generator. * * ## Notes * * - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective. * * @param {Options} [options] - options * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer * @throws {TypeError} state must be a `Uint32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} Mersenne Twister PRNG * * @example * var mt19937 = factory(); * * var v = mt19937(); * // returns <number> * * @example * // Return a seeded Mersenne Twister PRNG: * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isUint32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Uint32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else if ( isCollection( seed ) === false || seed.length < 1 ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } else if ( seed.length === 1 ) { seed = seed[ 0 ]; if ( !isPositiveInteger( seed ) ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else { slen = seed.length; STATE = new Uint32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createState( state, N, SEED_ARRAY_INIT_STATE ); state = initState( state, N, seed, slen ); } } else { seed = randuint32() >>> 0; // asm type annotation } } } else { seed = randuint32() >>> 0; // asm type annotation } if ( state === void 0 ) { STATE = new Uint32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createState( state, N, seed ); } // Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes). setReadOnly( mt19937, 'NAME', 'mt19937' ); setReadOnlyAccessor( mt19937, 'seed', getSeed ); setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength ); setReadWriteAccessor( mt19937, 'state', getState, setState ); setReadOnlyAccessor( mt19937, 'stateLength', getStateLength ); setReadOnlyAccessor( mt19937, 'byteLength', getStateSize ); setReadOnly( mt19937, 'toJSON', toJSON ); setReadOnly( mt19937, 'MIN', 1 ); setReadOnly( mt19937, 'MAX', UINT32_MAX ); setReadOnly( mt19937, 'normalized', normalized ); setReadOnly( normalized, 'NAME', mt19937.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', 0.0 ); setReadOnly( normalized, 'MAX', MAX_NORMALIZED ); return mt19937; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMT19937} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Uint32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. auxiliary state information * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMT19937} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Uint32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMT19937} s - generator state * @throws {TypeError} must provide a `Uint32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isUint32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Uint32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a new seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = mt19937.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * @private * @returns {uinteger32} pseudorandom integer * * @example * var r = mt19937(); * // returns <number> */ function mt19937() { var r; var i; // Retrieve the current state index: i = STATE[ OTHER_SECTION_OFFSET+1 ]; // Determine whether we need to update the PRNG state: if ( i >= N ) { state = twist( state ); i = 0; } // Get the next word of "raw"/untempered state: r = state[ i ]; // Update the state index: STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1; // Tempering transform to compensate for the reduced dimensionality of equidistribution: r ^= r >>> 11; r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1; r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2; r ^= r >>> 18; return r >>> 0; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * ## Notes * * - The original C implementation credits Isaku Wada for this algorithm (2002/01/09). * * @private * @returns {number} pseudorandom number * * @example * var r = normalized(); * // returns <number> */ function normalized() { var x = mt19937() >>> 5; var y = mt19937() >>> 6; return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_uint32.js":292,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":170,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/float64/max-safe-integer":240,"@stdlib/constants/uint32/max":250,"@stdlib/math/base/special/max":262,"@stdlib/math/base/special/uimul":269,"@stdlib/utils/define-nonenumerable-read-only-accessor":336,"@stdlib/utils/define-nonenumerable-read-only-property":338,"@stdlib/utils/define-nonenumerable-read-write-accessor":340}],290:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * A 32-bit Mersenne Twister pseudorandom number generator. * * @module @stdlib/random/base/mt19937 * * @example * var mt19937 = require( '@stdlib/random/base/mt19937' ); * * var v = mt19937(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/mt19937' ).factory; * * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var mt19937 = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( mt19937, 'factory', factory ); // EXPORTS // module.exports = mt19937; },{"./factory.js":289,"./main.js":291,"@stdlib/utils/define-nonenumerable-read-only-property":338}],291:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); var randuint32 = require( './rand_uint32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * ## Method * * - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits. * * - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits. * * - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\). * * - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer. * * - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then, * * ```javascript * x = 4294967295 >>> 5; // 00000111111111111111111111111111 * y = 4294967295 >>> 6; // 00000011111111111111111111111111 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111100000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111111111111111111111111111111 * ``` * * - Similarly, suppose the 32-bit PRNG generates the following values * * ```javascript * x = 1 >>> 5; // 0 => 00000000000000000000000000000000 * y = 64 >>> 6; // 1 => 00000000000000000000000000000001 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is * * ```binarystring * 0 00000000000 00000000000000000000 00000000000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 1 \\), which, in binary, is * * ```binarystring * 0 01111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers. * * * ## References * * - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a]. * - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>. * * [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995 * * * @function mt19937 * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = mt19937(); * // returns <number> */ var mt19937 = factory({ 'seed': randuint32() }); // EXPORTS // module.exports = mt19937; },{"./factory.js":289,"./rand_uint32.js":292}],292:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = UINT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randuint32(); * // returns <number> */ function randuint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v >>> 0; // asm type annotation } // EXPORTS // module.exports = randuint32; },{"@stdlib/constants/uint32/max":250,"@stdlib/math/base/special/floor":260}],293:[function(require,module,exports){ module.exports={ "name": "mt19937", "copy": true } },{}],294:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var typedarray2json = require( '@stdlib/array/to-json' ); var defaults = require( './defaults.json' ); var PRNGS = require( './prngs.js' ); // MAIN // /** * Returns a pseudorandom number generator for generating uniformly distributed random numbers on the interval \\( [0,1) \\). * * @param {Options} [options] - function options * @param {string} [options.name='mt19937'] - name of pseudorandom number generator * @param {*} [options.seed] - pseudorandom number generator seed * @param {*} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} must provide an object * @throws {TypeError} must provide valid options * @throws {Error} must provide the name of a supported pseudorandom number generator * @returns {PRNG} pseudorandom number generator * * @example * var uniform = factory(); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd' * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'seed': 12345 * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * var v = uniform(); * // returns <number> */ function factory( options ) { var opts; var rand; var prng; opts = { 'name': defaults.name, 'copy': defaults.copy }; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Must provide an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'name' ) ) { opts.name = options.name; } if ( hasOwnProp( options, 'state' ) ) { opts.state = options.state; if ( opts.state === void 0 ) { throw new TypeError( 'invalid option. `state` option cannot be undefined. Option: `' + opts.state + '`.' ); } } else if ( hasOwnProp( options, 'seed' ) ) { opts.seed = options.seed; if ( opts.seed === void 0 ) { throw new TypeError( 'invalid option. `seed` option cannot be undefined. Option: `' + opts.seed + '`.' ); } } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( opts.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' ); } } } prng = PRNGS[ opts.name ]; if ( prng === void 0 ) { throw new Error( 'invalid option. Unrecognized/unsupported PRNG. Option: `' + opts.name + '`.' ); } if ( opts.state === void 0 ) { if ( opts.seed === void 0 ) { rand = prng.factory(); } else { rand = prng.factory({ 'seed': opts.seed }); } } else { rand = prng.factory({ 'state': opts.state, 'copy': opts.copy }); } setReadOnly( uniform, 'NAME', 'randu' ); setReadOnlyAccessor( uniform, 'seed', getSeed ); setReadOnlyAccessor( uniform, 'seedLength', getSeedLength ); setReadWriteAccessor( uniform, 'state', getState, setState ); setReadOnlyAccessor( uniform, 'stateLength', getStateLength ); setReadOnlyAccessor( uniform, 'byteLength', getStateSize ); setReadOnly( uniform, 'toJSON', toJSON ); setReadOnly( uniform, 'PRNG', rand ); setReadOnly( uniform, 'MIN', rand.normalized.MIN ); setReadOnly( uniform, 'MAX', rand.normalized.MAX ); return uniform; /** * Returns the PRNG seed. * * @private * @returns {*} seed */ function getSeed() { return rand.seed; } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return rand.seedLength; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return rand.stateLength; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return rand.byteLength; } /** * Returns the current pseudorandom number generator state. * * @private * @returns {*} current state */ function getState() { return rand.state; } /** * Sets the pseudorandom number generator state. * * @private * @param {*} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { rand.state = s; } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = uniform.NAME + '-' + rand.NAME; out.state = typedarray2json( rand.state ); out.params = []; return out; } /** * Returns a uniformly distributed pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = uniform(); * // returns <number> */ function uniform() { return rand.normalized(); } } // EXPORTS // module.exports = factory; },{"./defaults.json":293,"./prngs.js":297,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/define-nonenumerable-read-only-accessor":336,"@stdlib/utils/define-nonenumerable-read-only-property":338,"@stdlib/utils/define-nonenumerable-read-write-accessor":340}],295:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Uniformly distributed pseudorandom numbers on the interval \\( [0,1) \\). * * @module @stdlib/random/base/randu * * @example * var randu = require( '@stdlib/random/base/randu' ); * * var v = randu(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/randu' ).factory; * * var randu = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * * var v = randu(); * // returns <number> */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var randu = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( randu, 'factory', factory ); // EXPORTS // module.exports = randu; },{"./factory.js":294,"./main.js":296,"@stdlib/utils/define-nonenumerable-read-only-property":338}],296:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); // MAIN // /** * Returns a uniformly distributed random number on the interval \\( [0,1) \\). * * @name randu * @type {PRNG} * @returns {number} pseudorandom number * * @example * var v = randu(); * // returns <number> */ var randu = factory(); // EXPORTS // module.exports = randu; },{"./factory.js":294}],297:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var prngs = {}; prngs[ 'minstd' ] = require( '@stdlib/random/base/minstd' ); prngs[ 'minstd-shuffle' ] = require( '@stdlib/random/base/minstd-shuffle' ); prngs[ 'mt19937' ] = require( '@stdlib/random/base/mt19937' ); // EXPORTS // module.exports = prngs; },{"@stdlib/random/base/minstd":286,"@stdlib/random/base/minstd-shuffle":282,"@stdlib/random/base/mt19937":290}],298:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Regular expression to match a newline character sequence. * * @module @stdlib/regexp/eol * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var RE_EOL = reEOL(); * * var bool = RE_EOL.test( '\n' ); * // returns true * * bool = RE_EOL.test( '\\r\\n' ); * // returns false * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var replace = require( '@stdlib/string/replace' ); * * var RE_EOL = reEOL({ * 'flags': 'g' * }); * var str = '1\n2\n3'; * var out = replace( str, RE_EOL, '' ); * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var bool = reEOL.REGEXP.test( '\r\n' ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reEOL = require( './main.js' ); var REGEXP_CAPTURE = require( './regexp_capture.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reEOL, 'REGEXP', REGEXP ); setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE ); // EXPORTS // module.exports = reEOL; },{"./main.js":299,"./regexp.js":300,"./regexp_capture.js":301,"@stdlib/utils/define-nonenumerable-read-only-property":338}],299:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var validate = require( './validate.js' ); // VARIABLES // var REGEXP_STRING = '\\r?\\n'; // MAIN // /** * Returns a regular expression to match a newline character sequence. * * @param {Options} [options] - function options * @param {string} [options.flags=''] - regular expression flags * @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {RegExp} regular expression * * @example * var RE_EOL = reEOL(); * var bool = RE_EOL.test( '\r\n' ); * // returns true * * @example * var replace = require( '@stdlib/string/replace' ); * * var RE_EOL = reEOL({ * 'flags': 'g' * }); * var str = '1\n2\n3'; * var out = replace( str, RE_EOL, '' ); */ function reEOL( options ) { var opts; var err; if ( arguments.length > 0 ) { opts = {}; err = validate( opts, options ); if ( err ) { throw err; } if ( opts.capture ) { return new RegExp( '('+REGEXP_STRING+')', opts.flags ); } return new RegExp( REGEXP_STRING, opts.flags ); } return /\r?\n/; } // EXPORTS // module.exports = reEOL; },{"./validate.js":302}],300:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var reEOL = require( './main.js' ); // MAIN // /** * Matches a newline character sequence. * * Regular expression: `/\r?\n/` * * - `\r?` * - match a carriage return character (optional) * * - `\n` * - match a line feed character * * @constant * @type {RegExp} * @default /\r?\n/ */ var REGEXP = reEOL(); // EXPORTS // module.exports = REGEXP; },{"./main.js":299}],301:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var reEOL = require( './main.js' ); // MAIN // /** * Captures a newline character sequence. * * Regular expression: `/\r?\n/` * * - `()` * - capture * * - `\r?` * - match a carriage return character (optional) * * - `\n` * - match a line feed character * * @constant * @type {RegExp} * @default /(\r?\n)/ */ var REGEXP_CAPTURE = reEOL({ 'capture': true }); // EXPORTS // module.exports = REGEXP_CAPTURE; },{"./main.js":299}],302:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {string} [options.flags] - regular expression flags * @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group * @returns {(Error|null)} null or an error object * * @example * var opts = {}; * var options = { * 'flags': 'gm' * }; * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'flags' ) ) { opts.flags = options.flags; if ( !isString( opts.flags ) ) { return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' ); } } if ( hasOwnProp( options, 'capture' ) ) { opts.capture = options.capture; if ( !isBoolean( opts.capture ) ) { return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],303:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; /** * Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * @module @stdlib/regexp/function-name * * @example * var reFunctionName = require( '@stdlib/regexp/function-name' ); * var RE_FUNCTION_NAME = reFunctionName(); * * function fname( fcn ) { * return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ]; * } * * var fn = fname( Math.sqrt ); * // returns 'sqrt' * * fn = fname( Int8Array ); * // returns 'Int8Array' * * fn = fname( Object.prototype.toString ); * // returns 'toString' * * fn = fname( function(){} ); * // returns '' */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reFunctionName = require( './main.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reFunctionName, 'REGEXP', REGEXP ); // EXPORTS // module.exports = reFunctionName; },{"./main.js":304,"./regexp.js":305,"@stdlib/utils/define-nonenumerable-read-only-property":338}],304:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * @returns {RegExp} regular expression * * @example * var RE_FUNCTION_NAME = reFunctionName(); * * function fname( fcn ) { * return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ]; * } * * var fn = fname( Math.sqrt ); * // returns 'sqrt' * * fn = fname( Int8Array ); * // returns 'Int8Array' * * fn = fname( Object.prototype.toString ); * // returns 'toString' * * fn = fname( function(){} ); * // returns '' */ function reFunctionName() { return /^\s*function\s*([^(]*)/i; } // EXPORTS // module.exports = reFunctionName; },{}],305:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var reFunctionName = require( './main.js' ); // MAIN // /** * Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * Regular expression: `/^\s*function\s*([^(]*)/i` * * - `/^\s*` * - Match zero or more spaces at beginning * * - `function` * - Match the word `function` * * - `\s*` * - Match zero or more spaces after the word `function` * * - `()` * - Capture * * - `[^(]*` * - Match anything except a left parenthesis `(` zero or more times * * - `/i` * - ignore case * * @constant * @type {RegExp} * @default /^\s*function\s*([^(]*)/i */ var RE_FUNCTION_NAME = reFunctionName(); // EXPORTS // module.exports = RE_FUNCTION_NAME; },{"./main.js":304}],306:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a regular expression to parse a regular expression string. * * @module @stdlib/regexp/regexp * * @example * var reRegExp = require( '@stdlib/regexp/regexp' ); * * var RE_REGEXP = reRegExp(); * * var bool = RE_REGEXP.test( '/^beep$/' ); * // returns true * * bool = RE_REGEXP.test( '' ); * // returns false * * @example * var reRegExp = require( '@stdlib/regexp/regexp' ); * * var RE_REGEXP = reRegExp(); * * var parts = RE_REGEXP.exec( '/^.*$/ig' ); * // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ] */ // MAIN // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reRegExp = require( './main.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reRegExp, 'REGEXP', REGEXP ); // EXPORTS // module.exports = reRegExp; // EXPORTS // module.exports = reRegExp; },{"./main.js":307,"./regexp.js":308,"@stdlib/utils/define-nonenumerable-read-only-property":338}],307:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns a regular expression to parse a regular expression string. * * @returns {RegExp} regular expression * * @example * var RE_REGEXP = reRegExp(); * * var bool = RE_REGEXP.test( '/^beep$/' ); * // returns true * * bool = RE_REGEXP.test( '' ); * // returns false */ function reRegExp() { return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape } // EXPORTS // module.exports = reRegExp; },{}],308:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var reRegExp = require( './main.js' ); // MAIN // /** * Matches parts of a regular expression string. * * Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/` * * - `/^\/` * - match a string that begins with a `/` * * - `()` * - capture * * - `(?:)+` * - capture, but do not remember, a group of characters which occur one or more times * * - `\\\/` * - match the literal `\/` * * - `|` * - OR * * - `[^\/]` * - anything which is not the literal `\/` * * - `\/` * - match the literal `/` * * - `([imgy]*)` * - capture any characters matching `imgy` occurring zero or more times * * - `$/` * - string end * * * @constant * @type {RegExp} * @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/ */ var RE_REGEXP = reRegExp(); // EXPORTS // module.exports = RE_REGEXP; },{"./main.js":307}],309:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var logger = require( 'debug' ); // VARIABLES // var debug = logger( 'transform-stream:transform' ); // MAIN // /** * Implements the `_transform` method as a pass through. * * @private * @param {(Uint8Array|Buffer|string)} chunk - streamed chunk * @param {string} encoding - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ function transform( chunk, encoding, clbk ) { debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding ); clbk( null, chunk ); } // EXPORTS // module.exports = transform; },{"debug":426}],310:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var logger = require( 'debug' ); var Transform = require( 'readable-stream' ).Transform; var inherit = require( '@stdlib/utils/inherit' ); var copy = require( '@stdlib/utils/copy' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var destroy = require( './destroy.js' ); var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle // VARIABLES // var debug = logger( 'transform-stream:ctor' ); // MAIN // /** * Transform stream constructor factory. * * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {Function} Transform stream constructor * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * * var TransformStream = ctor( opts ); * * var stream = new TransformStream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function ctor( options ) { var transform; var copts; var err; copts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( copts, options ); if ( err ) { throw err; } } if ( copts.transform ) { transform = copts.transform; } else { transform = _transform; } /** * Transform stream constructor. * * @private * @constructor * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = new TransformStream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function TransformStream( options ) { var opts; var err; if ( !( this instanceof TransformStream ) ) { if ( arguments.length ) { return new TransformStream( options ); } return new TransformStream(); } opts = copy( copts ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) ); Transform.call( this, opts ); this._destroyed = false; return this; } /** * Inherit from the `Transform` prototype. */ inherit( TransformStream, Transform ); /** * Implements the `_transform` method. * * @private * @name _transform * @memberof TransformStream.prototype * @type {Function} * @param {(Buffer|string)} chunk - streamed chunk * @param {string} encoding - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle if ( copts.flush ) { /** * Implements the `_flush` method. * * @private * @name _flush * @memberof TransformStream.prototype * @type {Function} * @param {Callback} callback to invoke after performing flush tasks */ TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle } /** * Gracefully destroys a stream, providing backward compatibility. * * @private * @name destroy * @memberof TransformStream.prototype * @type {Function} * @param {Object} [error] - optional error message * @returns {TransformStream} stream instance */ TransformStream.prototype.destroy = destroy; return TransformStream; } // EXPORTS // module.exports = ctor; },{"./_transform.js":309,"./defaults.json":311,"./destroy.js":312,"./validate.js":317,"@stdlib/utils/copy":334,"@stdlib/utils/inherit":370,"debug":426,"readable-stream":443}],311:[function(require,module,exports){ module.exports={ "objectMode": false, "encoding": null, "allowHalfOpen": false, "decodeStrings": true } },{}],312:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var logger = require( 'debug' ); var nextTick = require( '@stdlib/utils/next-tick' ); // VARIABLES // var debug = logger( 'transform-stream:destroy' ); // MAIN // /** * Gracefully destroys a stream, providing backward compatibility. * * @private * @param {Object} [error] - optional error message * @returns {Stream} stream instance */ function destroy( error ) { /* eslint-disable no-invalid-this */ var self; if ( this._destroyed ) { debug( 'Attempted to destroy an already destroyed stream.' ); return this; } self = this; this._destroyed = true; nextTick( close ); return this; /** * Closes a stream. * * @private */ function close() { if ( error ) { debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) ); self.emit( 'error', error ); } debug( 'Closing the stream...' ); self.emit( 'close' ); } } // EXPORTS // module.exports = destroy; },{"@stdlib/utils/next-tick":396,"debug":426}],313:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Creates a reusable transform stream factory. * * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @returns {Function} transform stream factory * * @example * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'objectMode': true, * 'encoding': 'utf8', * 'highWaterMark': 64, * 'decodeStrings': false * }; * * var factory = streamFactory( opts ); * * // Create 10 identically configured streams... * var streams = []; * var i; * for ( i = 0; i < 10; i++ ) { * streams.push( factory( transform ) ); * } */ function streamFactory( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } return createStream; /** * Creates a transform stream. * * @private * @param {Function} transform - callback to invoke upon receiving a new chunk * @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing * @throws {TypeError} must provide valid options * @throws {TypeError} transform callback must be a function * @throws {TypeError} flush callback must be a function * @returns {TransformStream} transform stream */ function createStream( transform, flush ) { opts.transform = transform; if ( arguments.length > 1 ) { opts.flush = flush; } else { delete opts.flush; // clear any previous `flush` } return new Stream( opts ); } } // EXPORTS // module.exports = streamFactory; },{"./main.js":315,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":334}],314:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Transform stream. * * @module @stdlib/streams/node/transform * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * var stream = transformStream( opts ); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * // => '1\n2\n3\n' * * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'objectMode': true, * 'encoding': 'utf8', * 'highWaterMark': 64, * 'decodeStrings': false * }; * * var factory = transformStream.factory( opts ); * * // Create 10 identically configured streams... * var streams = []; * var i; * for ( i = 0; i < 10; i++ ) { * streams.push( factory( transform ) ); * } * * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function stringify( chunk, enc, clbk ) { * clbk( null, JSON.stringify( chunk ) ); * } * * function newline( chunk, enc, clbk ) { * clbk( null, chunk+'\n' ); * } * * var s1 = transformStream.objectMode({ * 'transform': stringify * }); * * var s2 = transformStream.objectMode({ * 'transform': newline * }); * * s1.pipe( s2 ).pipe( stdout ); * * s1.write( {'value': 'a'} ); * s1.write( {'value': 'b'} ); * s1.write( {'value': 'c'} ); * * s1.end(); * // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' * * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * * var Stream = transformStream.ctor( opts ); * * var stream = new Stream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * // => '1\n2\n3\n' */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var transform = require( './main.js' ); var objectMode = require( './object_mode.js' ); var factory = require( './factory.js' ); var ctor = require( './ctor.js' ); // MAIN // setReadOnly( transform, 'objectMode', objectMode ); setReadOnly( transform, 'factory', factory ); setReadOnly( transform, 'ctor', ctor ); // EXPORTS // module.exports = transform; },{"./ctor.js":310,"./factory.js":313,"./main.js":315,"./object_mode.js":316,"@stdlib/utils/define-nonenumerable-read-only-property":338}],315:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var logger = require( 'debug' ); var Transform = require( 'readable-stream' ).Transform; var inherit = require( '@stdlib/utils/inherit' ); var copy = require( '@stdlib/utils/copy' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var destroy = require( './destroy.js' ); var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle // VARIABLES // var debug = logger( 'transform-stream:main' ); // MAIN // /** * Transform stream constructor. * * @constructor * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * var stream = new TransformStream( opts ); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function TransformStream( options ) { var opts; var err; if ( !( this instanceof TransformStream ) ) { if ( arguments.length ) { return new TransformStream( options ); } return new TransformStream(); } opts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) ); Transform.call( this, opts ); this._destroyed = false; if ( opts.transform ) { this._transform = opts.transform; } else { this._transform = _transform; } if ( opts.flush ) { this._flush = opts.flush; } return this; } /* * Inherit from the `Transform` prototype. */ inherit( TransformStream, Transform ); /** * Gracefully destroys a stream, providing backward compatibility. * * @name destroy * @memberof TransformStream.prototype * @type {Function} * @param {Object} [error] - optional error message * @returns {TransformStream} stream instance */ TransformStream.prototype.destroy = destroy; // EXPORTS // module.exports = TransformStream; },{"./_transform.js":309,"./defaults.json":311,"./destroy.js":312,"./validate.js":317,"@stdlib/utils/copy":334,"@stdlib/utils/inherit":370,"debug":426,"readable-stream":443}],316:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Returns a transform stream with `objectMode` set to `true`. * * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function stringify( chunk, enc, clbk ) { * clbk( null, JSON.stringify( chunk ) ); * } * * function newline( chunk, enc, clbk ) { * clbk( null, chunk+'\n' ); * } * * var s1 = objectMode({ * 'transform': stringify * }); * * var s2 = objectMode({ * 'transform': newline * }); * * s1.pipe( s2 ).pipe( stdout ); * * s1.write( {'value': 'a'} ); * s1.write( {'value': 'b'} ); * s1.write( {'value': 'c'} ); * * s1.end(); * * // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' */ function objectMode( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } opts.objectMode = true; return new Stream( opts ); } // EXPORTS // module.exports = objectMode; },{"./main.js":315,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":334}],317:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing * @returns {(Error|null)} null or an error object */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'transform' ) ) { opts.transform = options.transform; if ( !isFunction( opts.transform ) ) { return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' ); } } if ( hasOwnProp( options, 'flush' ) ) { opts.flush = options.flush; if ( !isFunction( opts.flush ) ) { return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' ); } } if ( hasOwnProp( options, 'objectMode' ) ) { opts.objectMode = options.objectMode; if ( !isBoolean( opts.objectMode ) ) { return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' ); } } if ( hasOwnProp( options, 'encoding' ) ) { opts.encoding = options.encoding; if ( !isString( opts.encoding ) ) { return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' ); } } if ( hasOwnProp( options, 'allowHalfOpen' ) ) { opts.allowHalfOpen = options.allowHalfOpen; if ( !isBoolean( opts.allowHalfOpen ) ) { return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' ); } } if ( hasOwnProp( options, 'highWaterMark' ) ) { opts.highWaterMark = options.highWaterMark; if ( !isNonNegative( opts.highWaterMark ) ) { return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' ); } } if ( hasOwnProp( options, 'decodeStrings' ) ) { opts.decodeStrings = options.decodeStrings; if ( !isBoolean( opts.decodeStrings ) ) { return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],318:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Create a string from a sequence of Unicode code points. * * @module @stdlib/string/from-code-point * * @example * var fromCodePoint = require( '@stdlib/string/from-code-point' ); * * var str = fromCodePoint( 9731 ); * // returns '☃' */ // MODULES // var fromCodePoint = require( './main.js' ); // EXPORTS // module.exports = fromCodePoint; },{"./main.js":319}],319:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var UNICODE_MAX = require( '@stdlib/constants/unicode/max' ); var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' ); // VARIABLES // var fromCharCode = String.fromCharCode; // Factor to rescale a code point from a supplementary plane: var Ox10000 = 0x10000|0; // 65536 // Factor added to obtain a high surrogate: var OxD800 = 0xD800|0; // 55296 // Factor added to obtain a low surrogate: var OxDC00 = 0xDC00|0; // 56320 // 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111 var Ox3FF = 1023|0; // MAIN // /** * Creates a string from a sequence of Unicode code points. * * ## Notes * * - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF). * - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate. * * * @param {...NonNegativeInteger} args - sequence of code points * @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments * @throws {TypeError} a code point must be a nonnegative integer * @throws {RangeError} must provide a valid Unicode code point * @returns {string} created string * * @example * var str = fromCodePoint( 9731 ); * // returns '☃' */ function fromCodePoint( args ) { var len; var str; var arr; var low; var hi; var pt; var i; len = arguments.length; if ( len === 1 && isCollection( args ) ) { arr = arguments[ 0 ]; len = arr.length; } else { arr = []; for ( i = 0; i < len; i++ ) { arr.push( arguments[ i ] ); } } if ( len === 0 ) { throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' ); } str = ''; for ( i = 0; i < len; i++ ) { pt = arr[ i ]; if ( !isNonNegativeInteger( pt ) ) { throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' ); } if ( pt > UNICODE_MAX ) { throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' ); } if ( pt <= UNICODE_MAX_BMP ) { str += fromCharCode( pt ); } else { // Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair). pt -= Ox10000; hi = (pt >> 10) + OxD800; low = (pt & Ox3FF) + OxDC00; str += fromCharCode( hi, low ); } } return str; } // EXPORTS // module.exports = fromCodePoint; },{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":253,"@stdlib/constants/unicode/max-bmp":252}],320:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Replace search occurrences with a replacement string. * * @module @stdlib/string/replace * * @example * var replace = require( '@stdlib/string/replace' ); * * var str = 'beep'; * var out = replace( str, 'e', 'o' ); * // returns 'boop' * * str = 'Hello World'; * out = replace( str, /world/i, 'Mr. President' ); * // returns 'Hello Mr. President' */ // MODULES // var replace = require( './replace.js' ); // EXPORTS // module.exports = replace; },{"./replace.js":321}],321:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var rescape = require( '@stdlib/utils/escape-regexp-string' ); var isFunction = require( '@stdlib/assert/is-function' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isRegExp = require( '@stdlib/assert/is-regexp' ); // MAIN // /** * Replace search occurrences with a replacement string. * * @param {string} str - input string * @param {(string|RegExp)} search - search expression * @param {(string|Function)} newval - replacement value or function * @throws {TypeError} first argument must be a string primitive * @throws {TypeError} second argument argument must be a string primitive or regular expression * @throws {TypeError} third argument must be a string primitive or function * @returns {string} new string containing replacement(s) * * @example * var str = 'beep'; * var out = replace( str, 'e', 'o' ); * // returns 'boop' * * @example * var str = 'Hello World'; * var out = replace( str, /world/i, 'Mr. President' ); * // returns 'Hello Mr. President' * * @example * var capitalize = require( '@stdlib/string/capitalize' ); * * var str = 'Oranges and lemons say the bells of St. Clement\'s'; * * function replacer( match, p1 ) { * return capitalize( p1 ); * } * * var out = replace( str, /([^\s]*)/gi, replacer); * // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s' */ function replace( str, search, newval ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' ); } if ( isString( search ) ) { search = rescape( search ); search = new RegExp( search, 'g' ); } else if ( !isRegExp( search ) ) { throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' ); } if ( !isString( newval ) && !isFunction( newval ) ) { throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' ); } return str.replace( search, newval ); } // EXPORTS // module.exports = replace; },{"@stdlib/assert/is-function":102,"@stdlib/assert/is-regexp":154,"@stdlib/assert/is-string":158,"@stdlib/utils/escape-regexp-string":347}],322:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Trim whitespace characters from the beginning and end of a string. * * @module @stdlib/string/trim * * @example * var trim = require( '@stdlib/string/trim' ); * * var out = trim( ' Whitespace ' ); * // returns 'Whitespace' * * out = trim( '\t\t\tTabs\t\t\t' ); * // returns 'Tabs' * * out = trim( '\n\n\nNew Lines\n\n\n' ); * // returns 'New Lines' */ // MODULES // var trim = require( './trim.js' ); // EXPORTS // module.exports = trim; },{"./trim.js":323}],323:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var replace = require( '@stdlib/string/replace' ); // VARIABLES // // The following regular expression should suffice to polyfill (most?) all environments. var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/; // MAIN // /** * Trim whitespace characters from beginning and end of a string. * * @param {string} str - input string * @throws {TypeError} must provide a string primitive * @returns {string} trimmed string * * @example * var out = trim( ' Whitespace ' ); * // returns 'Whitespace' * * @example * var out = trim( '\t\t\tTabs\t\t\t' ); * // returns 'Tabs' * * @example * var out = trim( '\n\n\nNew Lines\n\n\n' ); * // returns 'New Lines' */ function trim( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' ); } return replace( str, RE, '$1' ); } // EXPORTS // module.exports = trim; },{"@stdlib/assert/is-string":158,"@stdlib/string/replace":320}],324:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var getGlobal = require( '@stdlib/utils/global' ); var isObject = require( '@stdlib/assert/is-object' ); var modf = require( '@stdlib/math/base/special/modf' ); var round = require( '@stdlib/math/base/special/round' ); var now = require( './now.js' ); // VARIABLES // var Global = getGlobal(); var ts; var ns; if ( isObject( Global.performance ) ) { ns = Global.performance; } else { ns = {}; } if ( ns.now ) { ts = ns.now.bind( ns ); } else if ( ns.mozNow ) { ts = ns.mozNow.bind( ns ); } else if ( ns.msNow ) { ts = ns.msNow.bind( ns ); } else if ( ns.oNow ) { ts = ns.oNow.bind( ns ); } else if ( ns.webkitNow ) { ts = ns.webkitNow.bind( ns ); } else { ts = now; } // MAIN // /** * Returns a high-resolution time. * * ## Notes * * - Output format: `[seconds, nanoseconds]`. * * * @private * @returns {NumberArray} high-resolution time * * @example * var t = tic(); * // returns [<number>,<number>] */ function tic() { var parts; var t; // Get a millisecond timestamp and convert to seconds: t = ts() / 1000; // Decompose the timestamp into integer (seconds) and fractional parts: parts = modf( t ); // Convert the fractional part to nanoseconds: parts[ 1 ] = round( parts[1] * 1.0e9 ); // Return the high-resolution time: return parts; } // EXPORTS // module.exports = tic; },{"./now.js":326,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":264,"@stdlib/math/base/special/round":267,"@stdlib/utils/global":359}],325:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // var bool = isFunction( Date.now ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":102}],326:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var bool = require( './detect.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var now; if ( bool ) { now = Date.now; } else { now = polyfill; } // EXPORTS // module.exports = now; },{"./detect.js":325,"./polyfill.js":327}],327:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns the time in milliseconds since the epoch. * * @private * @returns {number} time * * @example * var ts = now(); * // returns <number> */ function now() { var d = new Date(); return d.getTime(); } // EXPORTS // module.exports = now; },{}],328:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a high-resolution time difference. * * @module @stdlib/time/toc * * @example * var tic = require( '@stdlib/time/tic' ); * var toc = require( '@stdlib/time/toc' ); * * var start = tic(); * var delta = toc( start ); * // returns [<number>,<number>] */ // MODULES // var toc = require( './toc.js' ); // EXPORTS // module.exports = toc; },{"./toc.js":329}],329:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives; var tic = require( '@stdlib/time/tic' ); // MAIN // /** * Returns a high-resolution time difference. * * ## Notes * * - Output format: `[seconds, nanoseconds]`. * * * @param {NonNegativeIntegerArray} time - high-resolution time * @throws {TypeError} must provide a nonnegative integer array * @throws {RangeError} input array must have length `2` * @returns {NumberArray} high resolution time difference * * @example * var tic = require( '@stdlib/time/tic' ); * * var start = tic(); * var delta = toc( start ); * // returns [<number>,<number>] */ function toc( time ) { var now = tic(); var sec; var ns; if ( !isNonNegativeIntegerArray( time ) ) { throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' ); } if ( time.length !== 2 ) { throw new RangeError( 'invalid argument. Input array must have length `2`.' ); } sec = now[ 0 ] - time[ 0 ]; ns = now[ 1 ] - time[ 1 ]; if ( sec > 0 && ns < 0 ) { sec -= 1; ns += 1e9; } else if ( sec < 0 && ns > 0 ) { sec += 1; ns -= 1e9; } return [ sec, ns ]; } // EXPORTS // module.exports = toc; },{"@stdlib/assert/is-nonnegative-integer-array":126,"@stdlib/time/tic":324}],330:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Determine the name of a value's constructor. * * @module @stdlib/utils/constructor-name * * @example * var constructorName = require( '@stdlib/utils/constructor-name' ); * * var v = constructorName( 'a' ); * // returns 'String' * * v = constructorName( {} ); * // returns 'Object' * * v = constructorName( true ); * // returns 'Boolean' */ // MODULES // var constructorName = require( './main.js' ); // EXPORTS // module.exports = constructorName; },{"./main.js":331}],331:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var RE = require( '@stdlib/regexp/function-name' ).REGEXP; var isBuffer = require( '@stdlib/assert/is-buffer' ); // MAIN // /** * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {string} name of a value's constructor * * @example * var v = constructorName( 'a' ); * // returns 'String' * * @example * var v = constructorName( 5 ); * // returns 'Number' * * @example * var v = constructorName( null ); * // returns 'Null' * * @example * var v = constructorName( undefined ); * // returns 'Undefined' * * @example * var v = constructorName( function noop() {} ); * // returns 'Function' */ function constructorName( v ) { var match; var name; var ctor; name = nativeClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } match = RE.exec( ctor.toString() ); if ( match ) { return match[ 1 ]; } } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // EXPORTS // module.exports = constructorName; },{"@stdlib/assert/is-buffer":88,"@stdlib/regexp/function-name":303,"@stdlib/utils/native-class":391}],332:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var PINF = require( '@stdlib/constants/float64/pinf' ); var deepCopy = require( './deep_copy.js' ); // MAIN // /** * Copies or deep clones a value to an arbitrary depth. * * @param {*} value - value to copy * @param {NonNegativeInteger} [level=+infinity] - copy depth * @throws {TypeError} `level` must be a nonnegative integer * @returns {*} value copy * * @example * var out = copy( 'beep' ); * // returns 'beep' * * @example * var value = [ * { * 'a': 1, * 'b': true, * 'c': [ 1, 2, 3 ] * } * ]; * var out = copy( value ); * // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] * * var bool = ( value[0].c === out[0].c ); * // returns false */ function copy( value, level ) { var out; if ( arguments.length > 1 ) { if ( !isNonNegativeInteger( level ) ) { throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' ); } if ( level === 0 ) { return value; } } else { level = PINF; } out = ( isArray( value ) ) ? new Array( value.length ) : {}; return deepCopy( value, out, [value], [out], level ); } // EXPORTS // module.exports = copy; },{"./deep_copy.js":333,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":242}],333:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isArray = require( '@stdlib/assert/is-array' ); var isBuffer = require( '@stdlib/assert/is-buffer' ); var isError = require( '@stdlib/assert/is-error' ); var typeOf = require( '@stdlib/utils/type-of' ); var regexp = require( '@stdlib/utils/regexp-from-string' ); var indexOf = require( '@stdlib/utils/index-of' ); var objectKeys = require( '@stdlib/utils/keys' ); var propertyNames = require( '@stdlib/utils/property-names' ); var propertyDescriptor = require( '@stdlib/utils/property-descriptor' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var defineProperty = require( '@stdlib/utils/define-property' ); var copyBuffer = require( '@stdlib/buffer/from-buffer' ); var typedArrays = require( './typed_arrays.js' ); // FUNCTIONS // /** * Clones a class instance. * * ## Notes * * - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**. * - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state. * * * @private * @param {Object} val - class instance * @returns {Object} new instance */ function cloneInstance( val ) { var cache; var names; var name; var refs; var desc; var tmp; var ref; var i; cache = []; refs = []; ref = Object.create( getPrototypeOf( val ) ); cache.push( val ); refs.push( ref ); names = propertyNames( val ); for ( i = 0; i < names.length; i++ ) { name = names[ i ]; desc = propertyDescriptor( val, name ); if ( hasOwnProp( desc, 'value' ) ) { tmp = ( isArray( val[name] ) ) ? [] : {}; desc.value = deepCopy( val[name], tmp, cache, refs, -1 ); } defineProperty( ref, name, desc ); } if ( !Object.isExtensible( val ) ) { Object.preventExtensions( ref ); } if ( Object.isSealed( val ) ) { Object.seal( ref ); } if ( Object.isFrozen( val ) ) { Object.freeze( ref ); } return ref; } /** * Copies an error object. * * @private * @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy * @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy * * @example * var err1 = new TypeError( 'beep' ); * * var err2 = copyError( err1 ); * // returns <TypeError> */ function copyError( error ) { var cache = []; var refs = []; var keys; var desc; var tmp; var key; var err; var i; // Create a new error... err = new error.constructor( error.message ); cache.push( error ); refs.push( err ); // If a `stack` property is present, copy it over... if ( error.stack ) { err.stack = error.stack; } // Node.js specific (system errors)... if ( error.code ) { err.code = error.code; } if ( error.errno ) { err.errno = error.errno; } if ( error.syscall ) { err.syscall = error.syscall; } // Any enumerable properties... keys = objectKeys( error ); for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; desc = propertyDescriptor( error, key ); if ( hasOwnProp( desc, 'value' ) ) { tmp = ( isArray( error[ key ] ) ) ? [] : {}; desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 ); } defineProperty( err, key, desc ); } return err; } // MAIN // /** * Recursively performs a deep copy of an input object. * * @private * @param {*} val - value to copy * @param {(Array|Object)} copy - copy * @param {Array} cache - an array of visited objects * @param {Array} refs - an array of object references * @param {NonNegativeInteger} level - copy depth * @returns {*} deep copy */ function deepCopy( val, copy, cache, refs, level ) { var parent; var keys; var name; var desc; var ctor; var key; var ref; var x; var i; var j; level -= 1; // Primitives and functions... if ( typeof val !== 'object' || val === null ) { return val; } if ( isBuffer( val ) ) { return copyBuffer( val ); } if ( isError( val ) ) { return copyError( val ); } // Objects... name = typeOf( val ); if ( name === 'date' ) { return new Date( +val ); } if ( name === 'regexp' ) { return regexp( val.toString() ); } if ( name === 'set' ) { return new Set( val ); } if ( name === 'map' ) { return new Map( val ); } if ( name === 'string' || name === 'boolean' || name === 'number' ) { // If provided an `Object`, return an equivalent primitive! return val.valueOf(); } ctor = typedArrays[ name ]; if ( ctor ) { return ctor( val ); } // Class instances... if ( name !== 'array' && name !== 'object' ) { // Cloning requires ES5 or higher... if ( typeof Object.freeze === 'function' ) { return cloneInstance( val ); } return {}; } // Arrays and plain objects... keys = objectKeys( val ); if ( level > 0 ) { parent = name; for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; x = val[ key ]; // Primitive, Buffer, special class instance... name = typeOf( x ); if ( typeof x !== 'object' || x === null || ( name !== 'array' && name !== 'object' ) || isBuffer( x ) ) { if ( parent === 'object' ) { desc = propertyDescriptor( val, key ); if ( hasOwnProp( desc, 'value' ) ) { desc.value = deepCopy( x ); } defineProperty( copy, key, desc ); } else { copy[ key ] = deepCopy( x ); } continue; } // Circular reference... i = indexOf( cache, x ); if ( i !== -1 ) { copy[ key ] = refs[ i ]; continue; } // Plain array or object... ref = ( isArray( x ) ) ? new Array( x.length ) : {}; cache.push( x ); refs.push( ref ); if ( parent === 'array' ) { copy[ key ] = deepCopy( x, ref, cache, refs, level ); } else { desc = propertyDescriptor( val, key ); if ( hasOwnProp( desc, 'value' ) ) { desc.value = deepCopy( x, ref, cache, refs, level ); } defineProperty( copy, key, desc ); } } } else if ( name === 'array' ) { for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; copy[ key ] = val[ key ]; } } else { for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; desc = propertyDescriptor( val, key ); defineProperty( copy, key, desc ); } } if ( !Object.isExtensible( val ) ) { Object.preventExtensions( copy ); } if ( Object.isSealed( val ) ) { Object.seal( copy ); } if ( Object.isFrozen( val ) ) { Object.freeze( copy ); } return copy; } // EXPORTS // module.exports = deepCopy; },{"./typed_arrays.js":335,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":232,"@stdlib/utils/define-property":345,"@stdlib/utils/get-prototype-of":353,"@stdlib/utils/index-of":367,"@stdlib/utils/keys":384,"@stdlib/utils/property-descriptor":406,"@stdlib/utils/property-names":410,"@stdlib/utils/regexp-from-string":413,"@stdlib/utils/type-of":418}],334:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Copy or deep clone a value to an arbitrary depth. * * @module @stdlib/utils/copy * * @example * var copy = require( '@stdlib/utils/copy' ); * * var out = copy( 'beep' ); * // returns 'beep' * * @example * var copy = require( '@stdlib/utils/copy' ); * * var value = [ * { * 'a': 1, * 'b': true, * 'c': [ 1, 2, 3 ] * } * ]; * var out = copy( value ); * // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] * * var bool = ( value[0].c === out[0].c ); * // returns false */ // MODULES // var copy = require( './copy.js' ); // EXPORTS // module.exports = copy; },{"./copy.js":332}],335:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var Int8Array = require( '@stdlib/array/int8' ); var Uint8Array = require( '@stdlib/array/uint8' ); var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); var Int16Array = require( '@stdlib/array/int16' ); var Uint16Array = require( '@stdlib/array/uint16' ); var Int32Array = require( '@stdlib/array/int32' ); var Uint32Array = require( '@stdlib/array/uint32' ); var Float32Array = require( '@stdlib/array/float32' ); var Float64Array = require( '@stdlib/array/float64' ); // VARIABLES // var hash; // FUNCTIONS // /** * Copies an `Int8Array`. * * @private * @param {Int8Array} arr - array to copy * @returns {Int8Array} new array */ function int8array( arr ) { return new Int8Array( arr ); } /** * Copies a `Uint8Array`. * * @private * @param {Uint8Array} arr - array to copy * @returns {Uint8Array} new array */ function uint8array( arr ) { return new Uint8Array( arr ); } /** * Copies a `Uint8ClampedArray`. * * @private * @param {Uint8ClampedArray} arr - array to copy * @returns {Uint8ClampedArray} new array */ function uint8clampedarray( arr ) { return new Uint8ClampedArray( arr ); } /** * Copies an `Int16Array`. * * @private * @param {Int16Array} arr - array to copy * @returns {Int16Array} new array */ function int16array( arr ) { return new Int16Array( arr ); } /** * Copies a `Uint16Array`. * * @private * @param {Uint16Array} arr - array to copy * @returns {Uint16Array} new array */ function uint16array( arr ) { return new Uint16Array( arr ); } /** * Copies an `Int32Array`. * * @private * @param {Int32Array} arr - array to copy * @returns {Int32Array} new array */ function int32array( arr ) { return new Int32Array( arr ); } /** * Copies a `Uint32Array`. * * @private * @param {Uint32Array} arr - array to copy * @returns {Uint32Array} new array */ function uint32array( arr ) { return new Uint32Array( arr ); } /** * Copies a `Float32Array`. * * @private * @param {Float32Array} arr - array to copy * @returns {Float32Array} new array */ function float32array( arr ) { return new Float32Array( arr ); } /** * Copies a `Float64Array`. * * @private * @param {Float64Array} arr - array to copy * @returns {Float64Array} new array */ function float64array( arr ) { return new Float64Array( arr ); } /** * Returns a hash of functions for copying typed arrays. * * @private * @returns {Object} function hash */ function typedarrays() { var out = { 'int8array': int8array, 'uint8array': uint8array, 'uint8clampedarray': uint8clampedarray, 'int16array': int16array, 'uint16array': uint16array, 'int32array': int32array, 'uint32array': uint32array, 'float32array': float32array, 'float64array': float64array }; return out; } // MAIN // hash = typedarrays(); // EXPORTS // module.exports = hash; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],336:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Define a non-enumerable read-only accessor. * * @module @stdlib/utils/define-nonenumerable-read-only-accessor * * @example * var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); * * function getter() { * return 'bar'; * } * * var obj = {}; * * setNonEnumerableReadOnlyAccessor( obj, 'foo', getter ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ // MODULES // var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length // EXPORTS // module.exports = setNonEnumerableReadOnlyAccessor; },{"./main.js":337}],337:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-only accessor. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Function} getter - accessor * * @example * function getter() { * return 'bar'; * } * * var obj = {}; * * setNonEnumerableReadOnlyAccessor( obj, 'foo', getter ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'get': getter }); } // EXPORTS // module.exports = setNonEnumerableReadOnlyAccessor; },{"@stdlib/utils/define-property":345}],338:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Define a non-enumerable read-only property. * * @module @stdlib/utils/define-nonenumerable-read-only-property * * @example * var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); * * var obj = {}; * * setNonEnumerableReadOnly( obj, 'foo', 'bar' ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ // MODULES // var setNonEnumerableReadOnly = require( './main.js' ); // EXPORTS // module.exports = setNonEnumerableReadOnly; },{"./main.js":339}],339:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-only property. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {*} value - value to set * * @example * var obj = {}; * * setNonEnumerableReadOnly( obj, 'foo', 'bar' ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ function setNonEnumerableReadOnly( obj, prop, value ) { defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'writable': false, 'value': value }); } // EXPORTS // module.exports = setNonEnumerableReadOnly; },{"@stdlib/utils/define-property":345}],340:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Define a non-enumerable read-write accessor. * * @module @stdlib/utils/define-nonenumerable-read-write-accessor * * @example * var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); * * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ // MODULES // var setNonEnumerableReadWriteAccessor = require( './main.js' ); // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"./main.js":341}],341:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-write accessor. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Function} getter - get accessor * @param {Function} setter - set accessor * * @example * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'get': getter, 'set': setter }); } // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"@stdlib/utils/define-property":345}],342:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Defines (or modifies) an object property. * * ## Notes * * - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both. * * @name defineProperty * @type {Function} * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Object} descriptor - property descriptor * @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object * @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties * @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator * @param {*} [descriptor.value] - property value * @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value. * @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned. * @throws {TypeError} first argument must be an object * @throws {TypeError} third argument must be an object * @throws {Error} property descriptor cannot have both a value and a setter and/or getter * @returns {Object} object with added property * * @example * var obj = {}; * * defineProperty( obj, 'foo', { * 'value': 'bar' * }); * * var str = obj.foo; * // returns 'bar' */ var defineProperty = Object.defineProperty; // EXPORTS // module.exports = defineProperty; },{}],343:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null; // EXPORTS // module.exports = main; },{}],344:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var defineProperty = require( './define_property.js' ); // MAIN // /** * Tests for `Object.defineProperty` support. * * @private * @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support * * @example * var bool = hasDefinePropertySupport(); * // returns <boolean> */ function hasDefinePropertySupport() { // Test basic support... try { defineProperty( {}, 'x', {} ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = hasDefinePropertySupport; },{"./define_property.js":343}],345:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Define (or modify) an object property. * * @module @stdlib/utils/define-property * * @example * var defineProperty = require( '@stdlib/utils/define-property' ); * * var obj = {}; * defineProperty( obj, 'foo', { * 'value': 'bar', * 'writable': false, * 'configurable': false, * 'enumerable': false * }); * obj.foo = 'boop'; // => throws */ // MODULES // var hasDefinePropertySupport = require( './has_define_property_support.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var defineProperty; if ( hasDefinePropertySupport() ) { defineProperty = builtin; } else { defineProperty = polyfill; } // EXPORTS // module.exports = defineProperty; },{"./builtin.js":342,"./has_define_property_support.js":344,"./polyfill.js":346}],346:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /* eslint-disable no-underscore-dangle, no-proto */ 'use strict'; // VARIABLES // var objectProtoype = Object.prototype; var toStr = objectProtoype.toString; var defineGetter = objectProtoype.__defineGetter__; var defineSetter = objectProtoype.__defineSetter__; var lookupGetter = objectProtoype.__lookupGetter__; var lookupSetter = objectProtoype.__lookupSetter__; // MAIN // /** * Defines (or modifies) an object property. * * ## Notes * * - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both. * * @param {Object} obj - object on which to define the property * @param {string} prop - property name * @param {Object} descriptor - property descriptor * @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object * @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties * @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator * @param {*} [descriptor.value] - property value * @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value. * @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned. * @throws {TypeError} first argument must be an object * @throws {TypeError} third argument must be an object * @throws {Error} property descriptor cannot have both a value and a setter and/or getter * @returns {Object} object with added property * * @example * var obj = {}; * * defineProperty( obj, 'foo', { * 'value': 'bar' * }); * * var str = obj.foo; * // returns 'bar' */ function defineProperty( obj, prop, descriptor ) { var prototype; var hasValue; var hasGet; var hasSet; if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' ); } if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) { throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' ); } hasValue = ( 'value' in descriptor ); if ( hasValue ) { if ( lookupGetter.call( obj, prop ) || lookupSetter.call( obj, prop ) ) { // Override `__proto__` to avoid touching inherited accessors: prototype = obj.__proto__; obj.__proto__ = objectProtoype; // Delete property as existing getters/setters prevent assigning value to specified property: delete obj[ prop ]; obj[ prop ] = descriptor.value; // Restore original prototype: obj.__proto__ = prototype; } else { obj[ prop ] = descriptor.value; } } hasGet = ( 'get' in descriptor ); hasSet = ( 'set' in descriptor ); if ( hasValue && ( hasGet || hasSet ) ) { throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' ); } if ( hasGet && defineGetter ) { defineGetter.call( obj, prop, descriptor.get ); } if ( hasSet && defineSetter ) { defineSetter.call( obj, prop, descriptor.set ); } return obj; } // EXPORTS // module.exports = defineProperty; },{}],347:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Escape a regular expression string or pattern. * * @module @stdlib/utils/escape-regexp-string * * @example * var rescape = require( '@stdlib/utils/escape-regexp-string' ); * * var str = rescape( '[A-Z]*' ); * // returns '\\[A\\-Z\\]\\*' */ // MODULES // var rescape = require( './main.js' ); // EXPORTS // module.exports = rescape; },{"./main.js":348}],348:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // VARIABLES // var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape // MAIN // /** * Escapes a regular expression string. * * @param {string} str - regular expression string * @throws {TypeError} first argument must be a string primitive * @returns {string} escaped string * * @example * var str = rescape( '[A-Z]*' ); * // returns '\\[A\\-Z\\]\\*' */ function rescape( str ) { var len; var s; var i; if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Check if the string starts with a forward slash... if ( str[ 0 ] === '/' ) { // Find the last forward slash... len = str.length; for ( i = len-1; i >= 0; i-- ) { if ( str[ i ] === '/' ) { break; } } } // If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`: if ( i === void 0 || i <= 0 ) { return str.replace( RE_CHARS, '\\$&' ); } // We need to de-construct the string... s = str.substring( 1, i ); // Only escape the characters between the `/`: s = s.replace( RE_CHARS, '\\$&' ); // Reassemble: str = str[ 0 ] + s + str.substring( i ); return str; } // EXPORTS // module.exports = rescape; },{"@stdlib/assert/is-string":158}],349:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); var RE = require( '@stdlib/regexp/function-name' ).REGEXP; // VARIABLES // var isFunctionNameSupported = hasFunctionNameSupport(); // MAIN // /** * Returns the name of a function. * * @param {Function} fcn - input function * @throws {TypeError} must provide a function * @returns {string} function name * * @example * var v = functionName( Math.sqrt ); * // returns 'sqrt' * * @example * var v = functionName( function foo(){} ); * // returns 'foo' * * @example * var v = functionName( function(){} ); * // returns '' || 'anonymous' * * @example * var v = functionName( String ); * // returns 'String' */ function functionName( fcn ) { // TODO: add support for generator functions? if ( isFunction( fcn ) === false ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' ); } if ( isFunctionNameSupported ) { return fcn.name; } return RE.exec( fcn.toString() )[ 1 ]; } // EXPORTS // module.exports = functionName; },{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":303}],350:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return the name of a function. * * @module @stdlib/utils/function-name * * @example * var functionName = require( '@stdlib/utils/function-name' ); * * var v = functionName( String ); * // returns 'String' * * v = functionName( function foo(){} ); * // returns 'foo' * * v = functionName( function(){} ); * // returns '' || 'anonymous' */ // MODULES // var functionName = require( './function_name.js' ); // EXPORTS // module.exports = functionName; },{"./function_name.js":349}],351:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var builtin = require( './native.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var getProto; if ( isFunction( Object.getPrototypeOf ) ) { getProto = builtin; } else { getProto = polyfill; } // EXPORTS // module.exports = getProto; },{"./native.js":354,"./polyfill.js":355,"@stdlib/assert/is-function":102}],352:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var getProto = require( './detect.js' ); // MAIN // /** * Returns the prototype of a provided object. * * @param {*} value - input value * @returns {(Object|null)} prototype * * @example * var proto = getPrototypeOf( {} ); * // returns {} */ function getPrototypeOf( value ) { if ( value === null || value === void 0 ) { return null; } // In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts: value = Object( value ); return getProto( value ); } // EXPORTS // module.exports = getPrototypeOf; },{"./detect.js":351}],353:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return the prototype of a provided object. * * @module @stdlib/utils/get-prototype-of * * @example * var getPrototype = require( '@stdlib/utils/get-prototype-of' ); * * var proto = getPrototype( {} ); * // returns {} */ // MODULES // var getPrototype = require( './get_prototype_of.js' ); // EXPORTS // module.exports = getPrototype; },{"./get_prototype_of.js":352}],354:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var getProto = Object.getPrototypeOf; // EXPORTS // module.exports = getProto; },{}],355:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var getProto = require( './proto.js' ); // MAIN // /** * Returns the prototype of a provided object. * * @private * @param {Object} obj - input object * @returns {(Object|null)} prototype */ function getPrototypeOf( obj ) { var proto = getProto( obj ); if ( proto || proto === null ) { return proto; } if ( nativeClass( obj.constructor ) === '[object Function]' ) { // May break if the constructor has been tampered with... return obj.constructor.prototype; } if ( obj instanceof Object ) { return Object.prototype; } // Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11. return null; } // EXPORTS // module.exports = getPrototypeOf; },{"./proto.js":356,"@stdlib/utils/native-class":391}],356:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Returns the value of the `__proto__` property. * * @private * @param {Object} obj - input object * @returns {*} value of `__proto__` property */ function getProto( obj ) { // eslint-disable-next-line no-proto return obj.__proto__; } // EXPORTS // module.exports = getProto; },{}],357:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns the global object using code generation. * * @private * @returns {Object} global object */ function getGlobal() { return new Function( 'return this;' )(); // eslint-disable-line no-new-func } // EXPORTS // module.exports = getGlobal; },{}],358:[function(require,module,exports){ (function (global){(function (){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var obj = ( typeof global === 'object' ) ? global : null; // EXPORTS // module.exports = obj; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],359:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return the global object. * * @module @stdlib/utils/global * * @example * var getGlobal = require( '@stdlib/utils/global' ); * * var g = getGlobal(); * // returns {...} */ // MODULES // var getGlobal = require( './main.js' ); // EXPORTS // module.exports = getGlobal; },{"./main.js":360}],360:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var getThis = require( './codegen.js' ); var Self = require( './self.js' ); var Win = require( './window.js' ); var Global = require( './global.js' ); // MAIN // /** * Returns the global object. * * ## Notes * * - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere. * * @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object * @throws {TypeError} must provide a boolean * @throws {Error} unable to resolve global object * @returns {Object} global object * * @example * var g = getGlobal(); * // returns {...} */ function getGlobal( codegen ) { if ( arguments.length ) { if ( !isBoolean( codegen ) ) { throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' ); } if ( codegen ) { return getThis(); } // Fall through... } // Case: browsers and web workers if ( Self ) { return Self; } // Case: browsers if ( Win ) { return Win; } // Case: Node.js if ( Global ) { return Global; } // Case: unknown throw new Error( 'unexpected error. Unable to resolve global object.' ); } // EXPORTS // module.exports = getGlobal; },{"./codegen.js":357,"./global.js":358,"./self.js":361,"./window.js":362,"@stdlib/assert/is-boolean":81}],361:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var obj = ( typeof self === 'object' ) ? self : null; // EXPORTS // module.exports = obj; },{}],362:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var obj = ( typeof window === 'object' ) ? window : null; // EXPORTS // module.exports = obj; },{}],363:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pkg = require( './../package.json' ).name; var ifelse = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var z; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { z = ifelse( randu() > 0.5, 1.0, -1.0 ); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); },{"./../lib":365,"./../package.json":366,"@stdlib/bench":224,"@stdlib/math/base/assert/is-nan":256,"@stdlib/random/base/randu":295}],364:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * If a condition is truthy, returns `x`; otherwise, returns `y`. * * @param {boolean} bool - condition * @param {*} x - value to return if a condition is truthy * @param {*} y - value to return if a condition is falsy * @returns {*} either `x` or `y` * * @example * var randu = require( '@stdlib/random/base/randu' ); * * var z = ifelse( randu() > 0.5, 1.0, -1.0 ); * // returns <number> */ function ifelse( bool, x, y ) { if ( bool ) { return x; } return y; } // EXPORTS // module.exports = ifelse; },{}],365:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * If a condition is truthy, return `x`; otherwise, return `y`. * * @module @stdlib/utils/if-else * * @example * var randu = require( '@stdlib/random/base/randu' ); * var ifelse = require( '@stdlib/utils/if-else' ); * * var z = ifelse( randu() > 0.5, 1.0, -1.0 ); * // returns <number> */ // MODULES // var ifelse = require( './if_else.js' ); // EXPORTS // module.exports = ifelse; },{"./if_else.js":364}],366:[function(require,module,exports){ module.exports={ "name": "@stdlib/utils/if-else", "version": "0.0.0", "description": "If a condition is truthy, return `x`; otherwise, return `y`.", "license": "Apache-2.0", "author": { "name": "The Stdlib Authors", "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" }, "contributors": [ { "name": "The Stdlib Authors", "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" } ], "main": "./lib", "directories": { "benchmark": "./benchmark", "doc": "./docs", "example": "./examples", "lib": "./lib", "test": "./test" }, "types": "./docs/types", "scripts": {}, "homepage": "https://github.com/stdlib-js/stdlib", "repository": { "type": "git", "url": "git://github.com/stdlib-js/stdlib.git" }, "bugs": { "url": "https://github.com/stdlib-js/stdlib/issues" }, "dependencies": {}, "devDependencies": {}, "engines": { "node": ">=0.10.0", "npm": ">2.7.0" }, "os": [ "aix", "darwin", "freebsd", "linux", "macos", "openbsd", "sunos", "win32", "windows" ], "keywords": [ "stdlib", "stdutils", "stdutil", "utilities", "utility", "utils", "util", "if", "else", "if-else", "control", "flow", "condition", "conditional", "either-or" ] } },{}],367:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return the first index at which a given element can be found. * * @module @stdlib/utils/index-of * * @example * var indexOf = require( '@stdlib/utils/index-of' ); * * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 3 ); * // returns 1 * * arr = [ 4, 3, 2, 1 ]; * idx = indexOf( arr, 5 ); * // returns -1 * * // Using a `fromIndex`: * arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * idx = indexOf( arr, 2, 3 ); * // returns 5 * * // `fromIndex` which exceeds `array` length: * arr = [ 1, 2, 3, 4, 2, 5 ]; * idx = indexOf( arr, 2, 10 ); * // returns -1 * * // Negative `fromIndex`: * arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ]; * idx = indexOf( arr, 2, -4 ); * // returns 5 * * idx = indexOf( arr, 2, -1 ); * // returns 7 * * // Negative `fromIndex` exceeding input `array` length: * arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * idx = indexOf( arr, 2, -10 ); * // returns 1 * * // Array-like objects: * var str = 'bebop'; * idx = indexOf( str, 'o' ); * // returns 3 */ // MODULES // var indexOf = require( './index_of.js' ); // EXPORTS // module.exports = indexOf; },{"./index_of.js":368}],368:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/assert/is-nan' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Returns the first index at which a given element can be found. * * @param {ArrayLike} arr - array-like object * @param {*} searchElement - element to find * @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element) * @throws {TypeError} must provide an array-like object * @throws {TypeError} `fromIndex` must be an integer * @returns {integer} index or -1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 3 ); * // returns 1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 5 ); * // returns -1 * * @example * // Using a `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, 3 ); * // returns 5 * * @example * // `fromIndex` which exceeds `array` length: * var arr = [ 1, 2, 3, 4, 2, 5 ]; * var idx = indexOf( arr, 2, 10 ); * // returns -1 * * @example * // Negative `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ]; * var idx = indexOf( arr, 2, -4 ); * // returns 5 * * idx = indexOf( arr, 2, -1 ); * // returns 7 * * @example * // Negative `fromIndex` exceeding input `array` length: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, -10 ); * // returns 1 * * @example * // Array-like objects: * var str = 'bebop'; * var idx = indexOf( str, 'o' ); * // returns 3 */ function indexOf( arr, searchElement, fromIndex ) { var len; var i; if ( !isCollection( arr ) && !isString( arr ) ) { throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' ); } len = arr.length; if ( len === 0 ) { return -1; } if ( arguments.length === 3 ) { if ( !isInteger( fromIndex ) ) { throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' ); } if ( fromIndex >= 0 ) { if ( fromIndex >= len ) { return -1; } i = fromIndex; } else { i = len + fromIndex; if ( i < 0 ) { i = 0; } } } else { i = 0; } // Check for `NaN`... if ( isnan( searchElement ) ) { for ( ; i < len; i++ ) { if ( isnan( arr[i] ) ) { return i; } } } else { for ( ; i < len; i++ ) { if ( arr[ i ] === searchElement ) { return i; } } } return -1; } // EXPORTS // module.exports = indexOf; },{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],369:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var builtin = require( './native.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var createObject; if ( typeof builtin === 'function' ) { createObject = builtin; } else { createObject = polyfill; } // EXPORTS // module.exports = createObject; },{"./native.js":372,"./polyfill.js":373}],370:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor. * * @module @stdlib/utils/inherit * * @example * var inherit = require( '@stdlib/utils/inherit' ); * * function Foo() { * return this; * } * Foo.prototype.beep = function beep() { * return 'boop'; * }; * * function Bar() { * Foo.call( this ); * return this; * } * inherit( Bar, Foo ); * * var bar = new Bar(); * var v = bar.beep(); * // returns 'boop' */ // MODULES // var inherit = require( './inherit.js' ); // EXPORTS // module.exports = inherit; },{"./inherit.js":371}],371:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); var validate = require( './validate.js' ); var createObject = require( './detect.js' ); // MAIN // /** * Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor. * * ## Notes * * - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`. * - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5). * * * @param {(Object|Function)} ctor - constructor which will inherit * @param {(Object|Function)} superCtor - super (parent) constructor * @throws {TypeError} first argument must be either an object or a function which can inherit * @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit * @throws {TypeError} second argument must have an inheritable prototype * @returns {(Object|Function)} child constructor * * @example * function Foo() { * return this; * } * Foo.prototype.beep = function beep() { * return 'boop'; * }; * * function Bar() { * Foo.call( this ); * return this; * } * inherit( Bar, Foo ); * * var bar = new Bar(); * var v = bar.beep(); * // returns 'boop' */ function inherit( ctor, superCtor ) { var err = validate( ctor ); if ( err ) { throw err; } err = validate( superCtor ); if ( err ) { throw err; } if ( typeof superCtor.prototype === 'undefined' ) { throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' ); } // Create a prototype which inherits from the parent prototype: ctor.prototype = createObject( superCtor.prototype ); // Set the constructor to refer to the child constructor: defineProperty( ctor.prototype, 'constructor', { 'configurable': true, 'enumerable': false, 'writable': true, 'value': ctor }); return ctor; } // EXPORTS // module.exports = inherit; },{"./detect.js":369,"./validate.js":374,"@stdlib/utils/define-property":345}],372:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // EXPORTS // module.exports = Object.create; },{}],373:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // FUNCTIONS // /** * Dummy constructor. * * @private */ function Ctor() { // Empty... } // MAIN // /** * An `Object.create` shim for older JavaScript engines. * * @private * @param {Object} proto - prototype * @returns {Object} created object * * @example * var obj = createObject( Object.prototype ); * // returns {} */ function createObject( proto ) { Ctor.prototype = proto; return new Ctor(); } // EXPORTS // module.exports = createObject; },{}],374:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Tests that a value is a valid constructor. * * @private * @param {*} value - value to test * @returns {(Error|null)} error object or null * * @example * var ctor = function ctor() {}; * * var err = validate( ctor ); * // returns null * * err = validate( null ); * // returns <TypeError> */ function validate( value ) { var type = typeof value; if ( value === null || (type !== 'object' && type !== 'function') ) { return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' ); } return null; } // EXPORTS // module.exports = validate; },{}],375:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Returns an array of an object's own enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { return Object.keys( Object( value ) ); } // EXPORTS // module.exports = keys; },{}],376:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isArguments = require( '@stdlib/assert/is-arguments' ); var builtin = require( './builtin.js' ); // VARIABLES // var slice = Array.prototype.slice; // MAIN // /** * Returns an array of an object's own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { if ( isArguments( value ) ) { return builtin( slice.call( value ) ); } return builtin( value ); } // EXPORTS // module.exports = keys; },{"./builtin.js":375,"@stdlib/assert/is-arguments":74}],377:[function(require,module,exports){ module.exports=[ "console", "external", "frame", "frameElement", "frames", "innerHeight", "innerWidth", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "scrollLeft", "scrollTop", "scrollX", "scrollY", "self", "webkitIndexedDB", "webkitStorageInfo", "window" ] },{}],378:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var keys = require( './builtin.js' ); // FUNCTIONS // /** * Tests the built-in `Object.keys()` implementation when provided `arguments`. * * @private * @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys */ function test() { return ( keys( arguments ) || '' ).length !== 2; } // MAIN // /** * Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value. * * ## Notes * * - Safari 5.0 does **not** support `arguments` as an input value. * * @private * @returns {boolean} boolean indicating whether a built-in implementation supports `arguments` */ function check() { return test( 1, 2 ); } // EXPORTS // module.exports = check; },{"./builtin.js":375}],379:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var indexOf = require( '@stdlib/utils/index-of' ); var typeOf = require( '@stdlib/utils/type-of' ); var isConstructorPrototype = require( './is_constructor_prototype.js' ); var EXCLUDED_KEYS = require( './excluded_keys.json' ); var win = require( './window.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]). * * [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable * * @private * @returns {boolean} boolean indicating whether an environment is buggy */ function check() { var k; if ( typeOf( win ) === 'undefined' ) { return false; } for ( k in win ) { // eslint-disable-line guard-for-in try { if ( indexOf( EXCLUDED_KEYS, k ) === -1 && hasOwnProp( win, k ) && win[ k ] !== null && typeOf( win[ k ] ) === 'object' ) { isConstructorPrototype( win[ k ] ); } } catch ( err ) { // eslint-disable-line no-unused-vars return true; } } return false; } // MAIN // bool = check(); // EXPORTS // module.exports = bool; },{"./excluded_keys.json":377,"./is_constructor_prototype.js":385,"./window.js":390,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":367,"@stdlib/utils/type-of":418}],380:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var bool = ( typeof Object.keys !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],381:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); var noop = require( '@stdlib/utils/noop' ); // MAIN // // Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be... var bool = isEnumerableProperty( noop, 'prototype' ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-enumerable-property":93,"@stdlib/utils/noop":398}],382:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); // VARIABLES // var obj = { 'toString': null }; // MAIN // // Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable... var bool = !isEnumerableProperty( obj, 'toString' ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-enumerable-property":93}],383:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var bool = ( typeof window !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],384:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return an array of an object's own enumerable property names. * * @module @stdlib/utils/keys * * @example * var keys = require( '@stdlib/utils/keys' ); * * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ // MODULES // var keys = require( './main.js' ); // EXPORTS // module.exports = keys; },{"./main.js":387}],385:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // /** * Tests whether a value equals the prototype of its constructor. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value equals the prototype of its constructor */ function isConstructorPrototype( value ) { return ( value.constructor && value.constructor.prototype === value ); } // EXPORTS // module.exports = isConstructorPrototype; },{}],386:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' ); var isConstructorPrototype = require( './is_constructor_prototype.js' ); var HAS_WINDOW = require( './has_window.js' ); // MAIN // /** * Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality). * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value equals the prototype of its constructor */ function wrapper( value ) { if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) { return isConstructorPrototype( value ); } try { return isConstructorPrototype( value ); } catch ( error ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = wrapper; },{"./has_automation_equality_bug.js":379,"./has_window.js":383,"./is_constructor_prototype.js":385}],387:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasArgumentsBug = require( './has_arguments_bug.js' ); var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var wrapper = require( './builtin_wrapper.js' ); var polyfill = require( './polyfill.js' ); // MAIN // /** * Returns an array of an object's own enumerable property names. * * @name keys * @type {Function} * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ var keys; if ( HAS_BUILTIN ) { if ( hasArgumentsBug() ) { keys = wrapper; } else { keys = builtin; } } else { keys = polyfill; } // EXPORTS // module.exports = keys; },{"./builtin.js":375,"./builtin_wrapper.js":376,"./has_arguments_bug.js":378,"./has_builtin.js":380,"./polyfill.js":389}],388:[function(require,module,exports){ module.exports=[ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ] },{}],389:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isObjectLike = require( '@stdlib/assert/is-object-like' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isArguments = require( '@stdlib/assert/is-arguments' ); var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' ); var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' ); var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' ); var NON_ENUMERABLE = require( './non_enumerable.json' ); // MAIN // /** * Returns an array of an object's own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { var skipConstructor; var skipPrototype; var isFcn; var out; var k; var p; var i; out = []; if ( isArguments( value ) ) { // Account for environments which treat `arguments` differently... for ( i = 0; i < value.length; i++ ) { out.push( i.toString() ); } // Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization). return out; } if ( typeof value === 'string' ) { // Account for environments which do not treat string character indices as "own" properties... if ( value.length > 0 && !hasOwnProp( value, '0' ) ) { for ( i = 0; i < value.length; i++ ) { out.push( i.toString() ); } } } else { isFcn = ( typeof value === 'function' ); if ( isFcn === false && !isObjectLike( value ) ) { return out; } skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn ); } for ( k in value ) { if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) { out.push( String( k ) ); } } if ( HAS_NON_ENUM_PROPS_BUG ) { skipConstructor = isConstructorPrototype( value ); for ( i = 0; i < NON_ENUMERABLE.length; i++ ) { p = NON_ENUMERABLE[ i ]; if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) { out.push( String( p ) ); } } } return out; } // EXPORTS // module.exports = keys; },{"./has_enumerable_prototype_bug.js":381,"./has_non_enumerable_properties_bug.js":382,"./is_constructor_prototype_wrapper.js":386,"./non_enumerable.json":388,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],390:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var w = ( typeof window === 'undefined' ) ? void 0 : window; // EXPORTS // module.exports = w; },{}],391:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a string value indicating a specification defined classification of an object. * * @module @stdlib/utils/native-class * * @example * var nativeClass = require( '@stdlib/utils/native-class' ); * * var str = nativeClass( 'a' ); * // returns '[object String]' * * str = nativeClass( 5 ); * // returns '[object Number]' * * function Beep() { * return this; * } * str = nativeClass( new Beep() ); * // returns '[object Object]' */ // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var builtin = require( './native_class.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var nativeClass; if ( hasToStringTag() ) { nativeClass = polyfill; } else { nativeClass = builtin; } // EXPORTS // module.exports = nativeClass; },{"./native_class.js":392,"./polyfill.js":393,"@stdlib/assert/has-tostringtag-support":57}],392:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var toStr = require( './tostring.js' ); // MAIN // /** * Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object. * * @param {*} v - input value * @returns {string} string value indicating a specification defined classification of the input value * * @example * var str = nativeClass( 'a' ); * // returns '[object String]' * * @example * var str = nativeClass( 5 ); * // returns '[object Number]' * * @example * function Beep() { * return this; * } * var str = nativeClass( new Beep() ); * // returns '[object Object]' */ function nativeClass( v ) { return toStr.call( v ); } // EXPORTS // module.exports = nativeClass; },{"./tostring.js":394}],393:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var toStringTag = require( './tostringtag.js' ); var toStr = require( './tostring.js' ); // MAIN // /** * Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`. * * @param {*} v - input value * @returns {string} string value indicating a specification defined classification of the input value * * @example * var str = nativeClass( 'a' ); * // returns '[object String]' * * @example * var str = nativeClass( 5 ); * // returns '[object Number]' * * @example * function Beep() { * return this; * } * var str = nativeClass( new Beep() ); * // returns '[object Object]' */ function nativeClass( v ) { var isOwn; var tag; var out; if ( v === null || v === void 0 ) { return toStr.call( v ); } tag = v[ toStringTag ]; isOwn = hasOwnProp( v, toStringTag ); // Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`. try { v[ toStringTag ] = void 0; } catch ( err ) { // eslint-disable-line no-unused-vars return toStr.call( v ); } out = toStr.call( v ); if ( isOwn ) { v[ toStringTag ] = tag; } else { delete v[ toStringTag ]; } return out; } // EXPORTS // module.exports = nativeClass; },{"./tostring.js":394,"./tostringtag.js":395,"@stdlib/assert/has-own-property":53}],394:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var toStr = Object.prototype.toString; // EXPORTS // module.exports = toStr; },{}],395:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : ''; // EXPORTS // module.exports = toStrTag; },{}],396:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ 'use strict'; /** * Add a callback to the "next tick queue". * * @module @stdlib/utils/next-tick * * @example * var nextTick = require( '@stdlib/utils/next-tick' ); * * function beep() { * console.log( 'boop' ); * } * * nextTick( beep ); */ // MODULES // var nextTick = require( './main.js' ); // EXPORTS // module.exports = nextTick; },{"./main.js":397}],397:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var proc = require( 'process' ); // MAIN // /** * Adds a callback to the "next tick queue". * * ## Notes * * - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue. * * @param {Callback} clbk - callback * @param {...*} [args] - arguments to provide to the callback upon invocation * * @example * function beep() { * console.log( 'boop' ); * } * * nextTick( beep ); */ function nextTick( clbk ) { var args; var i; args = []; for ( i = 1; i < arguments.length; i++ ) { args.push( arguments[ i ] ); } proc.nextTick( wrapper ); /** * Callback wrapper. * * ## Notes * * - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions. * * @private */ function wrapper() { clbk.apply( null, args ); } } // EXPORTS // module.exports = nextTick; },{"process":434}],398:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * No operation. * * @module @stdlib/utils/noop * * @example * var noop = require( '@stdlib/utils/noop' ); * * noop(); * // ...does nothing. */ // MODULES // var noop = require( './noop.js' ); // EXPORTS // module.exports = noop; },{"./noop.js":399}],399:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * No operation. * * @example * noop(); * // ...does nothing. */ function noop() { // Empty function... } // EXPORTS // module.exports = noop; },{}],400:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a partial object copy excluding specified keys. * * @module @stdlib/utils/omit * * @example * var omit = require( '@stdlib/utils/omit' ); * * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = omit( obj1, 'b' ); * // returns { 'a': 1 } */ // MODULES // var omit = require( './omit.js' ); // EXPORTS // module.exports = omit; },{"./omit.js":401}],401:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var objectKeys = require( '@stdlib/utils/keys' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var indexOf = require( '@stdlib/utils/index-of' ); // MAIN // /** * Returns a partial object copy excluding specified keys. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to exclude * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = omit( obj1, 'b' ); * // returns { 'a': 1 } */ function omit( obj, keys ) { var ownKeys; var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } ownKeys = objectKeys( obj ); out = {}; if ( isString( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( key !== keys ) { out[ key ] = obj[ key ]; } } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( indexOf( keys, key ) === -1 ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = omit; },{"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157,"@stdlib/utils/index-of":367,"@stdlib/utils/keys":384}],402:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a partial object copy containing only specified keys. * * @module @stdlib/utils/pick * * @example * var pick = require( '@stdlib/utils/pick' ); * * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = pick( obj1, 'b' ); * // returns { 'b': 2 } */ // MODULES // var pick = require( './pick.js' ); // EXPORTS // module.exports = pick; },{"./pick.js":403}],403:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to copy * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = pick( obj1, 'b' ); * // returns { 'b': 2 } */ function pick( obj, keys ) { var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } out = {}; if ( isString( keys ) ) { if ( hasOwnProp( obj, keys ) ) { out[ keys ] = obj[ keys ]; } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; if ( hasOwnProp( obj, key ) ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = pick; },{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157}],404:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // var propertyDescriptor = Object.getOwnPropertyDescriptor; // MAIN // /** * Returns a property descriptor for an object's own property. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error. * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`. * * @private * @param {*} value - input object * @param {(string|symbol)} property - property * @returns {(Object|null)} property descriptor or null * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var desc = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14} */ function getOwnPropertyDescriptor( value, property ) { var desc; if ( value === null || value === void 0 ) { return null; } desc = propertyDescriptor( value, property ); return ( desc === void 0 ) ? null : desc; } // EXPORTS // module.exports = getOwnPropertyDescriptor; },{}],405:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],406:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return a property descriptor for an object's own property. * * @module @stdlib/utils/property-descriptor * * @example * var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' ); * * var obj = { * 'foo': 'bar', * 'beep': 'boop' * }; * * var keys = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'} */ // MODULES // var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main; if ( HAS_BUILTIN ) { main = builtin; } else { main = polyfill; } // EXPORTS // module.exports = main; },{"./builtin.js":404,"./has_builtin.js":405,"./polyfill.js":407}],407:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Returns a property descriptor for an object's own property. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error. * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`. * - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`. * * @private * @param {*} value - input object * @param {(string|symbol)} property - property * @returns {(Object|null)} property descriptor or null * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var desc = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14} */ function getOwnPropertyDescriptor( value, property ) { if ( hasOwnProp( value, property ) ) { return { 'configurable': true, 'enumerable': true, 'writable': true, 'value': value[ property ] }; } return null; } // EXPORTS // module.exports = getOwnPropertyDescriptor; },{"@stdlib/assert/has-own-property":53}],408:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // VARIABLES // var propertyNames = Object.getOwnPropertyNames; // MAIN // /** * Returns an array of an object's own enumerable and non-enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * * @private * @param {*} value - input object * @returns {Array} a list of own property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var keys = getOwnPropertyNames( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function getOwnPropertyNames( value ) { return propertyNames( Object( value ) ); } // EXPORTS // module.exports = getOwnPropertyNames; },{}],409:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MAIN // var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],410:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Return an array of an object's own enumerable and non-enumerable property names. * * @module @stdlib/utils/property-names * * @example * var getOwnPropertyNames = require( '@stdlib/utils/property-names' ); * * var keys = getOwnPropertyNames({ * 'foo': 'bar', * 'beep': 'boop' * }); * // e.g., returns [ 'foo', 'beep' ] */ // MODULES // var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main; if ( HAS_BUILTIN ) { main = builtin; } else { main = polyfill; } // EXPORTS // module.exports = main; },{"./builtin.js":408,"./has_builtin.js":409,"./polyfill.js":411}],411:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var keys = require( '@stdlib/utils/keys' ); // MAIN // /** * Returns an array of an object's own enumerable and non-enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var keys = getOwnPropertyNames( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function getOwnPropertyNames( value ) { return keys( Object( value ) ); } // EXPORTS // module.exports = getOwnPropertyNames; },{"@stdlib/utils/keys":384}],412:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var reRegExp = require( '@stdlib/regexp/regexp' ); // MAIN // /** * Parses a regular expression string and returns a new regular expression. * * @param {string} str - regular expression string * @throws {TypeError} must provide a regular expression string * @returns {(RegExp|null)} regular expression or null * * @example * var re = reFromString( '/beep/' ); * // returns /beep/ */ function reFromString( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Capture the regular expression pattern and any flags: str = reRegExp().exec( str ); // Create a new regular expression: return ( str ) ? new RegExp( str[1], str[2] ) : null; } // EXPORTS // module.exports = reFromString; },{"@stdlib/assert/is-string":158,"@stdlib/regexp/regexp":306}],413:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Create a regular expression from a regular expression string. * * @module @stdlib/utils/regexp-from-string * * @example * var reFromString = require( '@stdlib/utils/regexp-from-string' ); * * var re = reFromString( '/beep/' ); * // returns /beep/ */ // MODULES // var reFromString = require( './from_string.js' ); // EXPORTS // module.exports = reFromString; },{"./from_string.js":412}],414:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var RE = require( './fixtures/re.js' ); var nodeList = require( './fixtures/nodelist.js' ); var typedarray = require( './fixtures/typedarray.js' ); // MAIN // /** * Checks whether a polyfill is needed when using the `typeof` operator. * * @private * @returns {boolean} boolean indicating whether a polyfill is needed */ function check() { if ( // Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof): typeof RE === 'function' || // Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929): typeof typedarray === 'object' || // PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236): typeof nodeList === 'function' ) { return true; } return false; } // EXPORTS // module.exports = check; },{"./fixtures/nodelist.js":415,"./fixtures/re.js":416,"./fixtures/typedarray.js":417}],415:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var getGlobal = require( '@stdlib/utils/global' ); // MAIN // var root = getGlobal(); var nodeList = root.document && root.document.childNodes; // EXPORTS // module.exports = nodeList; },{"@stdlib/utils/global":359}],416:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var RE = /./; // EXPORTS // module.exports = RE; },{}],417:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = typedarray; },{}],418:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; /** * Determine a value's type. * * @module @stdlib/utils/type-of * * @example * var typeOf = require( '@stdlib/utils/type-of' ); * * var str = typeOf( 'a' ); * // returns 'string' * * str = typeOf( 5 ); * // returns 'number' */ // MODULES // var usePolyfill = require( './check.js' ); var typeOf = require( './typeof.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main = ( usePolyfill() ) ? polyfill : typeOf; // EXPORTS // module.exports = main; },{"./check.js":414,"./polyfill.js":419,"./typeof.js":420}],419:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); // MAIN // /** * Determines a value's type. * * @param {*} v - input value * @returns {string} string indicating the value's type */ function typeOf( v ) { return ctorName( v ).toLowerCase(); } // EXPORTS // module.exports = typeOf; },{"@stdlib/utils/constructor-name":330}],420:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); // NOTES // /* * Built-in `typeof` operator behavior: * * ```text * typeof null => 'object' * typeof undefined => 'undefined' * typeof 'a' => 'string' * typeof 5 => 'number' * typeof NaN => 'number' * typeof true => 'boolean' * typeof false => 'boolean' * typeof {} => 'object' * typeof [] => 'object' * typeof function foo(){} => 'function' * typeof function* foo(){} => 'object' * typeof Symbol() => 'symbol' * ``` * */ // MAIN // /** * Determines a value's type. * * @param {*} v - input value * @returns {string} string indicating the value's type */ function typeOf( v ) { var type; // Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null): if ( v === null ) { return 'null'; } type = typeof v; // If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor. if ( type === 'object' ) { return ctorName( v ).toLowerCase(); } return type; } // EXPORTS // module.exports = typeOf; },{"@stdlib/utils/constructor-name":330}],421:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } },{}],422:[function(require,module,exports){ },{}],423:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); }; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } },{}],424:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this)}).call(this,require("buffer").Buffer) },{"base64-js":421,"buffer":424,"ieee754":428}],425:[function(require,module,exports){ (function (Buffer){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":430}],426:[function(require,module,exports){ (function (process){(function (){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }).call(this)}).call(this,require('_process')) },{"./debug":427,"_process":434}],427:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":432}],428:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],429:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } },{}],430:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],431:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],432:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],433:[function(require,module,exports){ (function (process){(function (){ 'use strict'; if (typeof process === 'undefined' || !process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this)}).call(this,require('_process')) },{"_process":434}],434:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(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; runClearTimeout(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) { runTimeout(drainQueue); } }; // 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.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } 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; }; },{}],435:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; },{"./_stream_readable":437,"./_stream_writable":439,"core-util-is":425,"inherits":429,"process-nextick-args":433}],436:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":438,"core-util-is":425,"inherits":429}],437:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ module.exports = Readable; /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /*</replacement>*/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._readableState.highWaterMark; } }); // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":435,"./internal/streams/BufferList":440,"./internal/streams/destroy":441,"./internal/streams/stream":442,"_process":434,"core-util-is":425,"events":423,"inherits":429,"isarray":431,"process-nextick-args":433,"safe-buffer":444,"string_decoder/":445,"util":422}],438:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":435,"core-util-is":425,"inherits":429}],439:[function(require,module,exports){ (function (process,global,setImmediate){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /*<replacement>*/ asyncWrite(afterWrite, stream, state, finished, cb); /*</replacement>*/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"./_stream_duplex":435,"./internal/streams/destroy":441,"./internal/streams/stream":442,"_process":434,"core-util-is":425,"inherits":429,"process-nextick-args":433,"safe-buffer":444,"timers":446,"util-deprecate":447}],440:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; var util = require('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":444,"util":422}],441:[function(require,module,exports){ 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { pna.nextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { pna.nextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":433}],442:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":423}],443:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":435,"./lib/_stream_passthrough.js":436,"./lib/_stream_readable.js":437,"./lib/_stream_transform.js":438,"./lib/_stream_writable.js":439}],444:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":424}],445:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; /*</replacement>*/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":444}],446:[function(require,module,exports){ (function (setImmediate,clearImmediate){(function (){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) },{"process/browser.js":434,"timers":446}],447:[function(require,module,exports){ (function (global){(function (){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[363]);
ajax/libs/rxjs/2.3.2/rx.compat.js
iamJoeTaylor/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; }; // 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 = { done: true, value: undefined }; /** `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; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } 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; 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; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ 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)); }); }; // Collection polyfills 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; }; } 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 Object.prototype.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 var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (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) { if (index === undefined) { 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(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * 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 BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; 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) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } 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; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * 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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; 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 () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } 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 invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * 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.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * 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). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { 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). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * 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); }; /** * 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 }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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'); }); }; /** 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) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; 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); } 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 scheduleMethod, clearMethod = noop; (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 setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * 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 = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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, 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 (exception) { var notification = new Notification('E'); notification.exception = exception; 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 enumerableFor = Enumerable.forEach = 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. * * @param observer Observer object. * @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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(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.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @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. * * @memberOf AbstractObserver * @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 (exception) { this._onError(exception); }; /** * 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; 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 (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); 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. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return 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)); }); }; /** * 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; }); }; /** * 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 new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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 Error('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; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * 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. */ 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 = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = 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(); } }); }); }; /** * 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 (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); 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 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @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 = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @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(); if (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 = argsOrArray(arguments, 0); 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 (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.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. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).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. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).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 = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (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; if (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 if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * 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 = argsOrArray(arguments, 0); 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), function () { self(); }, function () { 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 (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 if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * 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 (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. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @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) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.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) { try { if (!hasValue) { hasValue = true; } 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 () { if (!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); if (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. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @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(); }); }); }; /** * 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 (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * 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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; observableProto.concatMapObserver = 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; } observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }); }).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; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // 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 (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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 (exception) { observer.onError(exception); 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} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; 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; } observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * 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 observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.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; } } if (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 Error(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) { remaining--; observer.onNext(x); if (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. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(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 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 (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; 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 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 = []; } }, /** * 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) { 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)); 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));
docs/app/Examples/elements/Button/States/index.js
ben174/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ButtonStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Active' description='A button can show it is currently the active user selection.' examplePath='elements/Button/States/ButtonExampleActive' /> <ComponentExample title='Disabled' description='A button can show it is currently unable to be interacted with.' examplePath='elements/Button/States/ButtonExampleDisabled' /> <ComponentExample title='Loading' description='A button can show a loading indicator.' examplePath='elements/Button/States/ButtonExampleLoading' /> </ExampleSection> ) export default ButtonStatesExamples
examples/js/sort/custom-sort-table.js
neelvadgama-hailo/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } 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); function revertSortFunc(a, b, order) { // order is desc or asc if (order === 'desc') { return a.price - b.price; } else { return b.price - a.price; } } export default class CustomSortTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' dataSort={ true } sortFunc={ revertSortFunc }>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
packages/jQuery.1.10.2/Content/Scripts/jquery-1.10.2.js
mwhaubold/MettSite
/* 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. * * NUGET: END LICENSE TEXT */ /*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.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%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { 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>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.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( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
vendor/bundle/ruby/2.1.0/gems/sidekiq-3.3.0/web/assets/javascripts/application.js
suhongrui/gitlab
/*! jQuery v1.8.2 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,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(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.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=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",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){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);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{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._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)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.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,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.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,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.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):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.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;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),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){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(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(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);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=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.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){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),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(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),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)}}),p.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){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(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 bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(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){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); /** * Timeago is a jQuery plugin that makes it easy to support automatically * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago"). * * @name timeago * @version 0.11.1 * @requires jQuery v1.2.3+ * @author Ryan McGeary * @license MIT License - http://www.opensource.org/licenses/mit-license.php * * For usage and examples, visit: * http://timeago.yarp.com/ * * Copyright (c) 2008-2011, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org) */ (function(e){function n(){var t=r(this);if(!isNaN(t.datetime)){e(this).text(i(t.datetime))}return this}function r(n){n=e(n);if(!n.data("timeago")){n.data("timeago",{datetime:t.datetime(n)});var r=e.trim(n.text());if(r.length>0&&!(t.isTime(n)&&n.attr("title"))){n.attr("title",r)}}return n.data("timeago")}function i(e){return t.inWords(s(e))}function s(e){return(new Date).getTime()-e.getTime()}e.timeago=function(t){if(t instanceof Date){return i(t)}else if(typeof t==="string"){return i(e.timeago.parse(t))}else if(typeof t==="number"){return i(new Date(t))}else{return i(e.timeago.datetime(t))}};var t=e.timeago;e.extend(e.timeago,{settings:{refreshMillis:6e4,allowFuture:false,strings:{prefixAgo:null,prefixFromNow:null,suffixAgo:"ago",suffixFromNow:"from now",seconds:"less than a minute",minute:"about a minute",minutes:"%d minutes",hour:"about an hour",hours:"about %d hours",day:"a day",days:"%d days",month:"about a month",months:"%d months",year:"about a year",years:"%d years",wordSeparator:" ",numbers:[]}},inWords:function(t){function l(r,i){var s=e.isFunction(r)?r(i,t):r;var o=n.numbers&&n.numbers[i]||i;return s.replace(/%d/i,o)}var n=this.settings.strings;var r=n.prefixAgo;var i=n.suffixAgo;if(this.settings.allowFuture){if(t<0){r=n.prefixFromNow;i=n.suffixFromNow}}var s=Math.abs(t)/1e3;var o=s/60;var u=o/60;var a=u/24;var f=a/365;var c=s<45&&l(n.seconds,Math.round(s))||s<90&&l(n.minute,1)||o<45&&l(n.minutes,Math.round(o))||o<90&&l(n.hour,1)||u<24&&l(n.hours,Math.round(u))||u<42&&l(n.day,1)||a<30&&l(n.days,Math.round(a))||a<45&&l(n.month,1)||a<365&&l(n.months,Math.round(a/30))||f<1.5&&l(n.year,1)||l(n.years,Math.round(f));var h=n.wordSeparator===undefined?" ":n.wordSeparator;return e.trim([r,c,i].join(h))},parse:function(t){var n=e.trim(t);n=n.replace(/\.\d+/,"");n=n.replace(/-/,"/").replace(/-/,"/");n=n.replace(/T/," ").replace(/Z/," UTC");n=n.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2");return new Date(n)},datetime:function(n){var r=t.isTime(n)?e(n).attr("datetime"):e(n).attr("title");return t.parse(r)},isTime:function(t){return e(t).get(0).tagName.toLowerCase()==="time"}});e.fn.timeago=function(){var e=this;e.each(n);var r=t.settings;if(r.refreshMillis>0){setInterval(function(){e.each(n)},r.refreshMillis)}return e};document.createElement("abbr");document.createElement("time")})(jQuery) Sidekiq = {}; $(function() { $.timeago.settings.allowFuture = true; $.timeago.settings.refreshMillis = 0; $("time").timeago(); $(document).on('click', '.check_all', function() { var checked = $(this).attr('checked'); if (checked == 'checked') { $('input[type=checkbox]', $(this).closest('table')).attr('checked', checked); } else { $('input[type=checkbox]', $(this).closest('table')).removeAttr('checked'); } }); $(document).on("click", "[data-confirm]", function() { return confirm($(this).attr('data-confirm')); }); $(document).on("click", "[data-toggle]", function() { $($(this).attr('data-target')).toggle(); }); });
ajax/libs/6to5/1.14.9/browser-polyfill.js
cnbin/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(require,module,exports){(function(global){var ensureSymbol=function(key){Symbol[key]=Symbol[key]||Symbol()};var ensureProto=function(Constructor,key,val){var proto=Constructor.prototype;proto[key]=proto[key]||val};if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("./transformation/transformers/es6-generators/runtime");ensureSymbol("referenceGet");ensureSymbol("referenceSet");ensureSymbol("referenceDelete");ensureProto(Function,Symbol.referenceGet,function(){return this});ensureProto(Map,Symbol.referenceGet,Map.prototype.get);ensureProto(Map,Symbol.referenceSet,Map.prototype.set);ensureProto(Map,Symbol.referenceDelete,Map.prototype.delete);if(global.WeakMap){ensureProto(WeakMap,Symbol.referenceGet,WeakMap.prototype.get);ensureProto(WeakMap,Symbol.referenceSet,WeakMap.prototype.set);ensureProto(WeakMap,Symbol.referenceDelete,WeakMap.prototype.delete)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transformers/es6-generators/runtime":2,"es6-shim":4,"es6-symbol/implement":5}],2:[function(require,module,exports){(function(global){var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var runtime=global.regeneratorRuntime=exports;var hasOwn=Object.prototype.hasOwnProperty;var wrap=runtime.wrap=function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])};var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};var GF=function GeneratorFunction(){};var GFp=function GeneratorFunctionPrototype(){};var Gp=GFp.prototype=Generator.prototype;(GFp.constructor=GF).prototype=Gp.constructor=GFp;var GFName="GeneratorFunction";if(GF.name!==GFName)GF.name=GFName;if(GF.name!==GFName)throw new Error(GFName+" renamed?");runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GF.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var info;var value;try{info=this(arg);value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;var info;if(delegate){try{info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;var thrown;if(record.type==="throw"){thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],3:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],4:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}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){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");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;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 defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};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};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6-shim iterator_";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$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};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")}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){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="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(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){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)){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){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.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;if(v!==v){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){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}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("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){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("");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);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){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(_){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>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}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("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={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]:void 0;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]: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;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}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="…".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n \f\r   ᠎    ","          \u2028","\u2029"].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,"")}})}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(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<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?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){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}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);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}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}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 ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[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.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]: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}}}return},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")}};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}if(Array.prototype.keys&&Array.prototype.entries&&!Array.prototype.values&&Array.prototype[$iterator$]){defineProperties(Array.prototype,{values:Array.prototype[$iterator$]})}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});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){return value!==value}});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)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof 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,{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)},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{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}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.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){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}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){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;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(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};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]);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")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){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(){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)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){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;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){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}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;defineProperties(Promise,{"@@create":function(obj){var constructor=this;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}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};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)}}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){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);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);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}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}();if(globals.Promise){delete globals.Promise.accept;delete globals.Promise.defer;delete globals.Promise.prototype.chain}defineProperties(globals,{Promise:PromiseShim});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}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}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"]);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"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){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){i=i.prev}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}}}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);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});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;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){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}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){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){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}}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}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){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}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(){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()});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;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){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}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){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.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return 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){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([]);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)}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:3}],5:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":6,"./polyfill":21,"es5-ext/global":8}],6:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],7:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":9,"es5-ext/object/is-callable":12,"es5-ext/object/normalize-options":16,"es5-ext/string/#/contains":18}],8:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],9:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":10,"./shim":11}],10:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],11:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":13,"../valid-value":17}],12:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],13:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],15:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],16:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":9}],17:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],18:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],20:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],21:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:7}]},{},[1]);
ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.js
jonesgithub/cdnjs
/*! X-editable - v1.5.0 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = msg.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); var error, newValue = this.input.input2value(); //get new value from input //validation if (error = this.validate(newValue)) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'), values; if($.isEmptyObject(errors)) { values = this.editable('getValue'); if(config.data) { $.extend(values, config.data); } $.ajax($.extend({ url: config.url, data: values, type: 'POST' }, config.ajaxOptions)) .success(function(response) { //successful response 200 OK if(typeof config.success === 'function') { config.success.call($elems, response, config); } }) .error(function(){ //ajax error if(typeof config.error === 'function') { config.error.apply($elems, arguments); } }); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries' }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { //for local source use data directly from source (to allow autotext) /* if(!this.isRemote && !this.isMultiple) { var items = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); if(items.length) { this.$input.select2('data', items[0]); return; } } */ //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); } //if remote source AND no user's initSelection provided --> try to use element's text if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var data = {id: value, text: $(this.options.scope).text()}; this.$input.select2('data', data); } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.options.select2.separator || $.fn.select2.defaults.separator; var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.4 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For internalization include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(){ this.$element.val(this.getValue()); }, this)); this.$widget.find('select').css('width', 'auto'); //hide original input and insert widget this.$element.hide().after(this.$widget); //set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { var that = this; $.each(this.map, function(k, v) { var $c = that.$widget.find('.'+k), f, items; if($c.length) { that['$'+k] = $c; //set properties like this.$day, this.$month etc. f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); //define method name to fill items, e.g `fillDays` items = that[f](); that['$'+k].html(that.renderItems(items)); } }); }, /* Initialize items of combos. Handles `firstItem` option */ initItems: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* render items to string of <option> tags */ renderItems: function(items) { var str = []; for(var i=0; i<items.length; i++) { str.push('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } return str.join("\n"); }, /* fill day */ fillDay: function() { var items = this.initItems('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1; for(i=1; i<=31; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.initItems('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.initItems('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.initItems('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.initItems('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.initItems('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); this.$element.val(dt.format(this.options.format)); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true //whether to round minutes and seconds if step > 1 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on Twitter Bootstrap 3 */ (function ($) { "use strict"; //store parent methods var pInitInput = $.fn.editableform.Constructor.prototype.initInput; $.extend($.fn.editableform.Constructor.prototype, { initTemplate: function() { this.$form = $($.fn.editableform.template); this.$form.find('.control-group').addClass('form-group'); this.$form.find('.editable-error-block').addClass('help-block'); }, initInput: function() { pInitInput.apply(this); //for bs3 set default class `input-sm` to standard inputs var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false; var defaultClass = 'input-sm'; //bs3 add `form-control` class to standard inputs var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(','); if(~$.inArray(this.input.type, stdtypes)) { this.input.$input.addClass('form-control'); if(emptyInputClass) { this.input.options.inputclass = defaultClass; this.input.$input.addClass(defaultClass); } } //apply bs3 size class also to buttons (to fit size of control) var $btn = this.$form.find('.editable-buttons'); var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' '); for(var i=0; i<classes.length; i++) { // `btn-sm` is default now /* if(classes[i].toLowerCase() === 'input-sm') { $btn.find('button').addClass('btn-sm'); } */ if(classes[i].toLowerCase() === 'input-lg') { $btn.find('button').removeClass('btn-sm').addClass('btn-lg'); } } } }); //buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary btn-sm editable-submit">'+ '<i class="glyphicon glyphicon-ok"></i>'+ '</button>'+ '<button type="button" class="btn btn-default btn-sm editable-cancel">'+ '<i class="glyphicon glyphicon-remove"></i>'+ '</button>'; //error classes $.fn.editableform.errorGroupClass = 'has-error'; $.fn.editableform.errorBlockClass = null; //engine $.fn.editableform.engine = 'bs3'; }(window.jQuery)); /** * Editable Popover3 (for Bootstrap 3) * --------------------- * requires bootstrap-popover.js */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'popover', containerDataName: 'bs.popover', innerCss: '.popover-content', defaults: $.fn.popover.Constructor.DEFAULTS, initContainer: function(){ $.extend(this.containerOptions, { trigger: 'manual', selector: false, content: ' ', template: this.defaults.template }); //as template property is used in inputs, hide it from popover var t; if(this.$element.data('template')) { t = this.$element.data('template'); this.$element.removeData('template'); } this.call(this.containerOptions); if(t) { //restore data('template') this.$element.data('template', t); } }, /* show */ innerShow: function () { this.call('show'); }, /* hide */ innerHide: function () { this.call('hide'); }, /* destroy */ innerDestroy: function() { this.call('destroy'); }, setContainerOption: function(key, value) { this.container().options[key] = value; }, /** * move popover to new position. This function mainly copied from bootstrap-popover. */ /*jshint laxcomma: true, eqeqeq: false*/ setPosition: function () { (function() { /* var $tip = this.tip() , inside , pos , actualWidth , actualHeight , placement , tp , tpt , tpb , tpl , tpr; placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; inside = /in/.test(placement); $tip // .detach() //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover .removeClass('top right bottom left') .css({ top: 0, left: 0, display: 'block' }); // .insertAfter(this.$element); pos = this.getPosition(inside); actualWidth = $tip[0].offsetWidth; actualHeight = $tip[0].offsetHeight; placement = inside ? placement.split(' ')[1] : placement; tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}; tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}; tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}; tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}; switch (placement) { case 'bottom': if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) { if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'top': if (tpt.top < $(window).scrollTop()) { if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) { placement = 'bottom'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'left': if (tpl.left < $(window).scrollLeft()) { if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } else { placement = 'right'; } } break; case 'right': if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) { if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } } break; } switch (placement) { case 'bottom': tp = tpb; break; case 'top': tp = tpt; break; case 'left': tp = tpl; break; case 'right': tp = tpr; break; } $tip .offset(tp) .addClass(placement) .addClass('in'); */ var $tip = this.tip(); var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; var pos = this.getPosition(); var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight); this.applyPlacement(calculatedOffset, placement); }).call(this.container()); /*jshint laxcomma: false, eqeqeq: true*/ } }); }(window.jQuery)); /* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * 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. * ========================================================= */ (function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if(this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this.o.startDate); this.setEndDate(this.o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch(o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format) if (o.startDate !== -Infinity) { o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } if (o.endDate !== Infinity) { o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function(){ if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).size() || this.picker.is(e.target) || this.picker.find(e.target).size() )) { this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.date, local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000)); this.element.trigger({ type: event, date: local_date, format: $.proxy(function(altformat){ var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function() { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if(fromArgs) this.setValue(); if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if(this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1){ cls.push('selected'); } } return cls; }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if(this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); var before = this.o.beforeShowDay(prevMonth); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } else { var year = parseInt(target.text(), 10)||0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.date; }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]){ // Date being moved earlier/left while (i>=0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i<l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; var datepicker = $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else{ $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it datepicker.call($this, 'show'); } ); $(function(){ //$('[data-provide="datepicker-inline"]').datepicker(); //vit: changed to support noConflict() datepicker.call($('[data-provide="datepicker-inline"]')); }); }( window.jQuery )); /** Bootstrap-datepicker. Description and examples: https://github.com/eternicode/bootstrap-datepicker. For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales and set `language` option. Since 1.4.0 date has different appearance in **popup** and **inline** modes. @class date @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one $.fn.bdatepicker = $.fn.datepicker.noConflict(); if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name $.fn.datepicker = $.fn.bdatepicker; } var Date = function (options) { this.init('date', options, Date.defaults); this.initPicker(options, Date.defaults); }; $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput); $.extend(Date.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datepicker config defined as json string in data-datepicker options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { format: this.options.viewformat }); //language this.options.datepicker.language = this.options.datepicker.language || 'en'; //store DPglobal this.dpg = $.fn.bdatepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat); }, render: function () { this.$input.bdatepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''; Date.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.parseDate(html, this.parsedViewFormat); }, value2str: function(value) { return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : ''; }, str2value: function(str) { return this.parseDate(str, this.parsedFormat); }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.bdatepicker('update', value); }, input2value: function() { return this.$input.data('datepicker').date; }, activate: function() { }, clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.day', function(e){ if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) { return; } var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); //changedate is not suitable as it triggered when showing datepicker. see #149 /* this.$input.on('changeDate', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); */ }, /* For incorrect date bootstrap-datepicker returns current date that is not suitable for datefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datepicker.language); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language); if(str !== formattedBack) { date = null; } } } return date; } }); Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code> @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://vitalets.github.com/bootstrap-datepicker @property datepicker @type object @default { weekStart: 0, startView: 0, minViewMode: 0, autoclose: false } **/ datepicker:{ weekStart: 0, startView: 0, minViewMode: 0, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.date = Date; }(window.jQuery)); /** Bootstrap datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class datefield @extends date @since 1.4.0 **/ (function ($) { "use strict"; var DateField = function (options) { this.init('datefield', options, DateField.defaults); this.initPicker(options, DateField.defaults); }; $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date); $.extend(DateField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js) this.$tpl.bdatepicker(this.options.datepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.bdatepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''); this.$tpl.bdatepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-small' **/ inputclass: 'input-small', /* datepicker config */ datepicker: { weekStart: 0, startView: 0, minViewMode: 0, autoclose: true } }); $.fn.editabletypes.datefield = DateField; }(window.jQuery)); /** Bootstrap-datetimepicker. Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). Before usage you should manually include dependent js and css: <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> <script src="js/bootstrap-datetimepicker.js"></script> For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales and set `language` option. @class datetime @extends abstractinput @final @since 1.4.4 @example <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a> <script> $(function(){ $('#last_seen').editable({ format: 'yyyy-mm-dd hh:ii', viewformat: 'dd/mm/yyyy hh:ii', datetimepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateTime = function (options) { this.init('datetime', options, DateTime.defaults); this.initPicker(options, DateTime.defaults); }; $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput); $.extend(DateTime.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datetimepicker config defined as json string in data-datetimepicker options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true); //overriding datetimepicker config (as by default jQuery extend() is not recursive) //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, { format: this.options.viewformat }); //language this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; //store DPglobal this.dpg = $.fn.datetimepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType); }, render: function () { this.$input.datetimepicker(this.options.datetimepicker); //adjust container position when viewMode changes //see https://github.com/smalot/bootstrap-datetimepicker/pull/80 this.$input.on('changeMode', function(e) { var f = $(this).closest('form').parent(); //timeout here, otherwise container changes position before form has new size setTimeout(function(){ f.triggerHandler('resize'); }, 0); }); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { //formatDate works with UTCDate! var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : ''; if(element) { DateTime.superclass.value2html.call(this, text, element); } else { return text; } }, html2value: function(html) { //parseDate return utc date! var value = this.parseDate(html, this.parsedViewFormat); return value ? this.fromUTC(value) : null; }, value2str: function(value) { //formatDate works with UTCDate! return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : ''; }, str2value: function(str) { //parseDate return utc date! var value = this.parseDate(str, this.parsedFormat); return value ? this.fromUTC(value) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { if(value) { this.$input.data('datetimepicker').setDate(value); } }, input2value: function() { //date may be cleared, in that case getDate() triggers error var dt = this.$input.data('datetimepicker'); return dt.date ? dt.getDate() : null; }, activate: function() { }, clear: function() { this.$input.data('datetimepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.minute', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); }, //convert date from local to utc toUTC: function(value) { return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value; }, //convert date from utc to local fromUTC: function(value) { return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value; }, /* For incorrect date bootstrap-datetimepicker returns current date that is not suitable for datetimefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType); if(str !== formattedBack) { date = null; } } } return date; } }); DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code> @property format @type string @default yyyy-mm-dd hh:ii **/ format:'yyyy-mm-dd hh:ii', formatType:'standard', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datetimepicker. Full list of options: https://github.com/smalot/bootstrap-datetimepicker @property datetimepicker @type object @default { } **/ datetimepicker:{ todayHighlight: false, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.datetime = DateTime; }(window.jQuery)); /** Bootstrap datetimefield input - datetime input for inline mode. Shows normal <input type="text"> and binds popup datetimepicker. Automatically shown in inline mode. @class datetimefield @extends datetime **/ (function ($) { "use strict"; var DateTimeField = function (options) { this.init('datetimefield', options, DateTimeField.defaults); this.initPicker(options, DateTimeField.defaults); }; $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime); $.extend(DateTimeField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); this.$tpl.datetimepicker(this.options.datetimepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.datetimepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(this.value2html(value)); this.$tpl.datetimepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-medium' **/ inputclass: 'input-medium', /* datetimepicker config */ datetimepicker:{ todayHighlight: false, autoclose: true } }); $.fn.editabletypes.datetimefield = DateTimeField; }(window.jQuery));