);
- },
-
- handleClick: function (e) {
- if (this.props.onSelect) {
- e.preventDefault();
-
- if (!this.props.disabled) {
- this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
- }
- }
}
-});
-
-module.exports = NavItem;
+}
diff --git a/common/app/components/NotFound/index.js b/common/app/components/NotFound/index.js
new file mode 100644
index 0000000000..8206b46115
--- /dev/null
+++ b/common/app/components/NotFound/index.js
@@ -0,0 +1,14 @@
+import React from 'react';
+
+export default class extends React.Component {
+ constructor(props) {
+ super(props);
+ }
+ static displayName = 'NotFound'
+ static propTypes = {}
+ componentDidMount() {
+ }
+ render() {
+ return null;
+ }
+}
diff --git a/common/app/routes/Jobs/index.js b/common/app/routes/Jobs/index.js
index 44813f34f6..b18ca761d8 100644
--- a/common/app/routes/Jobs/index.js
+++ b/common/app/routes/Jobs/index.js
@@ -12,7 +12,7 @@ export default {
getComponents(cb) {
require.ensure([], require => {
cb(null, [
- require('./components/Jobs')
+ require('./components/Jobs.jsx')
]);
});
}
diff --git a/gulpfile.js b/gulpfile.js
index 12750f55d2..5c1ec16675 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -12,6 +12,11 @@ var gulp = require('gulp'),
envify = require('envify/custom'),
toVinylWithName = require('vinyl-source-stream'),
+ // react app
+ webpack = require('gulp-webpack'),
+ webpackConfig = require('./webpack.config.js'),
+ webpackConfigNode = require('./webpack.config.node.js'),
+
// server process
nodemon = require('gulp-nodemon'),
sync = require('browser-sync'),
@@ -41,6 +46,16 @@ var paths = {
clientName: 'lbApp'
},
+ client: {
+ src: './client',
+ dest: 'public/js'
+ },
+
+ node: {
+ src: './client',
+ dest: 'server/server'
+ },
+
syncWatch: [
'public/**/*.*'
]
@@ -83,6 +98,20 @@ gulp.task('loopback', function() {
.pipe(gulp.dest(paths.publicJs));
});
+gulp.task('pack-client', function() {
+ return gulp.src(paths.client.src)
+ .pipe(webpack(webpackConfig))
+ .pipe(gulp.dest(paths.client.dest));
+});
+
+gulp.task('pack-node', function() {
+ return gulp.src(paths.node.src)
+ .pipe(webpack(webpackConfigNode))
+ .pipe(gulp.dest(paths.node.dest));
+});
+
+gulp.task('pack', ['pack-client', 'pack-node']);
+
gulp.task('serve', function(cb) {
var called = false;
nodemon({
diff --git a/package.json b/package.json
index f38ef4c2c1..174cb4a1bd 100644
--- a/package.json
+++ b/package.json
@@ -29,10 +29,13 @@
"dependencies": {
"accepts": "~1.2.5",
"async": "~0.9.0",
+ "babel-core": "^5.6.15",
+ "babel-loader": "^5.2.2",
"bcrypt-nodejs": "~0.0.3",
"body-parser": "~1.9.3",
"chai-jquery": "~2.0.0",
"cheerio": "~0.18.0",
+ "classnames": "^2.1.2",
"clockwork": "~0.1.1",
"compression": "~1.2.1",
"connect-mongo": "~0.7.0",
@@ -45,16 +48,20 @@
"express": "~4.10.4",
"express-flash": "~0.0.2",
"express-session": "~1.9.2",
+ "express-state": "^1.2.0",
"express-validator": "~2.8.0",
+ "fetchr": "^0.4.16",
"font-awesome": "~4.3.0",
"forever": "~0.14.1",
"frameguard": "^0.2.2",
"github-api": "~0.7.0",
"gulp-less": "^3.0.3",
"gulp-minify-css": "~0.5.1",
+ "gulp-webpack": "^1.5.0",
"helmet": "~0.9.0",
"helmet-csp": "^0.2.3",
"jade": "~1.8.0",
+ "json-loader": "^0.5.2",
"less": "~1.7.5",
"less-middleware": "~2.0.1",
"lodash": "^3.9.3",
@@ -67,6 +74,7 @@
"moment": "~2.10.2",
"mongodb": "^2.0.33",
"morgan": "~1.5.0",
+ "node-libs-browser": "^0.5.2",
"node-slack": "0.0.7",
"node-uuid": "^1.4.3",
"nodemailer": "~1.3.0",
@@ -80,15 +88,17 @@
"pmx": "^0.3.16",
"ramda": "~0.10.0",
"react": "^0.13.3",
- "react-bootstrap": "^0.23.4",
+ "react-bootstrap": "^0.23.5",
"react-router": "^1.0.0-beta1",
"request": "~2.53.0",
"rx": "^2.5.3",
"sanitize-html": "~1.6.1",
+ "source-map-support": "^0.3.2",
"thundercats": "^2.0.0-rc6",
"twit": "~1.1.20",
"uglify-js": "~2.4.15",
"validator": "~3.22.1",
+ "webpack": "^1.9.12",
"yui": "~3.18.1"
},
"devDependencies": {
diff --git a/server/boot/a-react.js b/server/boot/a-react.js
new file mode 100644
index 0000000000..ac0f32ee09
--- /dev/null
+++ b/server/boot/a-react.js
@@ -0,0 +1,57 @@
+// appFactory is an es6 module
+var debug = require('debug')('freecc:servereact');
+var app$ = require('../common/app/app-stream.jsx').default;
+var Cat = require('thundercats').Cat;
+
+var routes = [
+ '/jobs'
+];
+
+module.exports = function(app) {
+ var router = app.Router();
+
+ routes.forEach(function(route) {
+ router.get(route, serveReactApp);
+ });
+
+ app.use(router);
+
+ function serveReactApp(req, res, next) {
+ var fcc = new Cat();
+ var decodedUrl = decodeURI(req.path);
+
+ // returns a router wrapped app
+ app$(decodedUrl)
+ // if react-router does not find a route send down the chain
+ .filter(function(data) {
+ var state = data.state;
+ // this may not work with react-router 1.0.0
+ var notFound = state.routes.some(route => route.isNotFound);
+ if (notFound) {
+ debug('tried to find %s but got 404', state.path);
+ next();
+ }
+ return !notFound;
+ })
+ .flatMap(function(app) {
+ // call thundercats renderToString
+ // prefetches data and sets up it up for current state
+ return fcc.renderToString(app);
+ })
+ // makes sure we only get one onNext and closes subscription
+ .firstOrDefault()
+ .flatMap(function(dats) {
+ debug('react rendered');
+ res.expose(dats.data, 'data');
+ // now render jade file with markup injected from react
+ return res.render$('layout-react', { markup: dats.markup });
+ })
+ .subscribe(
+ function(markup) {
+ debug('jade rendered');
+ res.send(markup);
+ },
+ next
+ );
+ }
+};
diff --git a/server/server.js b/server/server.js
index 51f0047aeb..44e47a9ca7 100755
--- a/server/server.js
+++ b/server/server.js
@@ -22,6 +22,7 @@ var R = require('ramda'),
lessMiddleware = require('less-middleware'),
passportProviders = require('./passport-providers'),
+ rxMiddleware = require('./utils/rx').rxMiddleware,
/**
* API keys and Passport configuration.
*/
@@ -175,19 +176,22 @@ app.use(helmet.csp({
passportConfigurator.init();
+// add rx methods to express
+app.use(rxMiddleware());
+
app.use(function(req, res, next) {
// Make user object available in templates.
res.locals.user = req.user;
next();
});
+
app.use(
loopback.static(path.join(__dirname, '../public'), {
maxAge: 86400000
})
);
-// track when connecting to db starts
var startTime = Date.now();
boot(app, {
appRootDir: __dirname,
diff --git a/server/server/1.fcc.js b/server/server/1.fcc.js
new file mode 100644
index 0000000000..a527ffb99d
--- /dev/null
+++ b/server/server/1.fcc.js
@@ -0,0 +1,79 @@
+exports.ids = [1];
+exports.modules = {
+
+/***/ 309:
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
+
+ var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
+
+ var _react = __webpack_require__(53);
+
+ var _react2 = _interopRequireDefault(_react);
+
+ var _thundercats = __webpack_require__(22);
+
+ var _reactBootstrap = __webpack_require__(233);
+
+ var _default = (function (_React$Component) {
+ var _class = function _default(props) {
+ _classCallCheck(this, _class2);
+
+ _get(Object.getPrototypeOf(_class2.prototype), 'constructor', this).call(this, props);
+ };
+
+ _inherits(_class, _React$Component);
+
+ var _class2 = _class;
+
+ _createClass(_class2, [{
+ key: 'render',
+ value: function render() {
+ return _react2['default'].createElement(
+ _reactBootstrap.Grid,
+ null,
+ _react2['default'].createElement(
+ _reactBootstrap.Row,
+ null,
+ 'foo'
+ )
+ );
+ }
+ }], [{
+ key: 'displayName',
+ value: 'Jobs',
+ enumerable: true
+ }, {
+ key: 'propTypes',
+ value: {
+ jobs: _react.PropTypes.array
+ },
+ enumerable: true
+ }]);
+
+ _class = (0, _thundercats.createContainer)({
+ store: 'JobsStore'
+ })(_class) || _class;
+ return _class;
+ })(_react2['default'].Component);
+
+ exports['default'] = _default;
+ module.exports = exports['default'];
+
+/***/ }
+
+};;
+//# sourceMappingURL=1.fcc.js.map
\ No newline at end of file
diff --git a/server/server/1.fcc.js.map b/server/server/1.fcc.js.map
new file mode 100644
index 0000000000..ad8928495d
--- /dev/null
+++ b/server/server/1.fcc.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["webpack:///./common/app/routes/Jobs/components/Jobs.jsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;kCAAiC,EAAO;;;;wCACR,EAAa;;2CACnB,GAAiB;;;gBAM9B,kBAAC,KAAK,EAAE;;;AACjB,oFAAM,KAAK,EAAE;IACd;;;;;;;;YAQK,kBAAG;AACP,cACE;yBAlBG,IAAI;;SAmBL;2BAnBO,GAAG;;;UAqBJ;QACD,CACP;MACH;;;YAboB,MAAM;;;;YACR;AACjB,WAAI,EAAE,OAfM,SAAS,CAeL,KAAK;MACtB;;;;YAZF,iBAHQ,eAAe,EAGP;AACf,UAAK,EAAE,WAAW;IACnB,CAAC;;IAC2B,mBAAM,SAAS","file":"1.fcc.js","sourcesContent":["import React, { PropTypes } from 'react';\nimport { createContainer } from 'thundercats';\nimport { Grid, Row } from 'react-bootstrap';\n\n@createContainer({\n store: 'JobsStore'\n})\nexport default class extends React.Component {\n constructor(props) {\n super(props);\n }\n\n\n static displayName = 'Jobs'\n static propTypes = {\n jobs: PropTypes.array\n }\n\n render() {\n return (\n \n \n foo\n \n \n );\n }\n}\n\n\n\n/** WEBPACK FOOTER **\n ** ./common/app/routes/Jobs/components/Jobs.jsx\n **/"],"sourceRoot":""}
\ No newline at end of file
diff --git a/server/server/fcc.js b/server/server/fcc.js
new file mode 100644
index 0000000000..f234026622
--- /dev/null
+++ b/server/server/fcc.js
@@ -0,0 +1,46548 @@
+/******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // object to store loaded chunks
+/******/ // "1" means "already loaded"
+/******/ var installedChunks = {
+/******/ 0:1
+/******/ };
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId])
+/******/ return installedModules[moduleId].exports;
+/******/
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ exports: {},
+/******/ id: moduleId,
+/******/ loaded: false
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.loaded = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/ // This file contains only the entry chunk.
+/******/ // The chunk loading function for additional chunks
+/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
+/******/ // "1" is the signal for "already loaded"
+/******/ if(!installedChunks[chunkId]) {
+/******/ var chunk = require("./" + chunkId + ".fcc.js");
+/******/ var moreModules = chunk.modules, chunkIds = chunk.ids;
+/******/ for(var moduleId in moreModules) {
+/******/ modules[moduleId] = moreModules[moduleId];
+/******/ }
+/******/ for(var i = 0; i < chunkIds.length; i++)
+/******/ installedChunks[chunkIds[i]] = 1;
+/******/ }
+/******/ callback.call(null, __webpack_require__);
+/******/ };
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "public/";
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _reactRouterLibBrowserHistory = __webpack_require__(1);
+
+ var _reactRouterLibBrowserHistory2 = _interopRequireDefault(_reactRouterLibBrowserHistory);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _thundercats = __webpack_require__(22);
+
+ var _commonAppAppFactoryJsx = __webpack_require__(213);
+
+ var _commonAppAppFactoryJsx2 = _interopRequireDefault(_commonAppAppFactoryJsx);
+
+ var debug = (0, _debug2['default'])('fcc:client');
+ var DOMContianer = document.getElemenetById('#fCC');
+ var fcc = new _thundercats.Cat();
+
+ // returns an observable
+ fcc.render((0, _commonAppAppFactoryJsx2['default'])(_reactRouterLibBrowserHistory2['default']), DOMContianer).subscribe(function () {
+ debug('react rendered');
+ }, function (err) {
+ debug('an error has occured', err.stack);
+ });
+
+/***/ },
+/* 1 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
+
+ var _DOMHistory2 = __webpack_require__(2);
+
+ var _DOMHistory3 = _interopRequireDefault(_DOMHistory2);
+
+ var _DOMUtils = __webpack_require__(14);
+
+ var _NavigationTypes = __webpack_require__(12);
+
+ var _NavigationTypes2 = _interopRequireDefault(_NavigationTypes);
+
+ function updateCurrentState(extraState) {
+ var state = window.history.state;
+
+ if (state) window.history.replaceState(_extends(state, extraState), '');
+ }
+
+ /**
+ * A history implementation for DOM environments that support the
+ * HTML5 history API (pushState, replaceState, and the popstate event).
+ * Provides the cleanest URLs and should always be used in browser
+ * environments if possible.
+ *
+ * Note: BrowserHistory automatically falls back to using full page
+ * refreshes if HTML5 history is not available, so URLs are always
+ * the same across browsers.
+ */
+
+ var BrowserHistory = (function (_DOMHistory) {
+ function BrowserHistory(options) {
+ _classCallCheck(this, BrowserHistory);
+
+ _DOMHistory.call(this, options);
+ this.handlePopState = this.handlePopState.bind(this);
+ this.isSupported = (0, _DOMUtils.supportsHistory)();
+ }
+
+ _inherits(BrowserHistory, _DOMHistory);
+
+ BrowserHistory.prototype._updateLocation = function _updateLocation(navigationType) {
+ var state = null;
+
+ if (this.isSupported) {
+ var historyState = window.history.state;
+ state = this._createState(historyState);
+
+ if (!historyState || !historyState.key) window.history.replaceState(state, '');
+ }
+
+ this.location = this.createLocation((0, _DOMUtils.getWindowPath)(), state, navigationType);
+ };
+
+ BrowserHistory.prototype.setup = function setup() {
+ if (this.location == null) this._updateLocation();
+ };
+
+ BrowserHistory.prototype.handlePopState = function handlePopState(event) {
+ if (event.state === undefined) return; // Ignore extraneous popstate events in WebKit.
+
+ this._updateLocation(_NavigationTypes2['default'].POP);
+ this._notifyChange();
+ };
+
+ BrowserHistory.prototype.addChangeListener = function addChangeListener(listener) {
+ _DOMHistory.prototype.addChangeListener.call(this, listener);
+
+ if (this.changeListeners.length === 1) {
+ if (window.addEventListener) {
+ window.addEventListener('popstate', this.handlePopState, false);
+ } else {
+ window.attachEvent('onpopstate', this.handlePopState);
+ }
+ }
+ };
+
+ BrowserHistory.prototype.removeChangeListener = function removeChangeListener(listener) {
+ _DOMHistory.prototype.removeChangeListener.call(this, listener);
+
+ if (this.changeListeners.length === 0) {
+ if (window.removeEventListener) {
+ window.removeEventListener('popstate', this.handlePopState, false);
+ } else {
+ window.removeEvent('onpopstate', this.handlePopState);
+ }
+ }
+ };
+
+ // http://www.w3.org/TR/2011/WD-html5-20110113/history.html#dom-history-pushstate
+
+ BrowserHistory.prototype.pushState = function pushState(state, path) {
+ if (this.isSupported) {
+ updateCurrentState(this.getScrollPosition());
+
+ state = this._createState(state);
+
+ window.history.pushState(state, '', path);
+ this.location = this.createLocation(path, state, _NavigationTypes2['default'].PUSH);
+ this._notifyChange();
+ } else {
+ window.location = path;
+ }
+ };
+
+ // http://www.w3.org/TR/2011/WD-html5-20110113/history.html#dom-history-replacestate
+
+ BrowserHistory.prototype.replaceState = function replaceState(state, path) {
+ if (this.isSupported) {
+ state = this._createState(state);
+
+ window.history.replaceState(state, '', path);
+ this.location = this.createLocation(path, state, _NavigationTypes2['default'].REPLACE);
+ this._notifyChange();
+ } else {
+ window.location.replace(path);
+ }
+ };
+
+ return BrowserHistory;
+ })(_DOMHistory3['default']);
+
+ exports['default'] = BrowserHistory;
+ module.exports = exports['default'];
+
+/***/ },
+/* 2 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
+
+ var _History2 = __webpack_require__(3);
+
+ var _History3 = _interopRequireDefault(_History2);
+
+ var _DOMUtils = __webpack_require__(14);
+
+ /**
+ * A history interface that assumes a DOM environment.
+ */
+
+ var DOMHistory = (function (_History) {
+ function DOMHistory() {
+ var options = arguments[0] === undefined ? {} : arguments[0];
+
+ _classCallCheck(this, DOMHistory);
+
+ _History.call(this, options);
+ this.getScrollPosition = options.getScrollPosition || _DOMUtils.getWindowScrollPosition;
+ }
+
+ _inherits(DOMHistory, _History);
+
+ DOMHistory.prototype.go = function go(n) {
+ if (n === 0) return;
+
+ window.history.go(n);
+ };
+
+ return DOMHistory;
+ })(_History3['default']);
+
+ exports['default'] = DOMHistory;
+ module.exports = exports['default'];
+
+/***/ },
+/* 3 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ var _invariant = __webpack_require__(4);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var _URLUtils = __webpack_require__(5);
+
+ var _Location = __webpack_require__(11);
+
+ var _Location2 = _interopRequireDefault(_Location);
+
+ var RequiredHistorySubclassMethods = ['pushState', 'replaceState', 'go'];
+
+ function createRandomKey() {
+ return Math.random().toString(36).substr(2);
+ }
+
+ /**
+ * A history interface that normalizes the differences across
+ * various environments and implementations. Requires concrete
+ * subclasses to implement the following methods:
+ *
+ * - pushState(state, path)
+ * - replaceState(state, path)
+ * - go(n)
+ */
+
+ var History = (function () {
+ function History() {
+ var options = arguments[0] === undefined ? {} : arguments[0];
+
+ _classCallCheck(this, History);
+
+ RequiredHistorySubclassMethods.forEach(function (method) {
+ (0, _invariant2['default'])(typeof this[method] === 'function', '%s needs a "%s" method', this.constructor.name, method);
+ }, this);
+
+ this.parseQueryString = options.parseQueryString || _URLUtils.parseQueryString;
+ this.changeListeners = [];
+ this.location = null;
+ }
+
+ History.prototype._notifyChange = function _notifyChange() {
+ for (var i = 0, len = this.changeListeners.length; i < len; ++i) this.changeListeners[i].call(this);
+ };
+
+ History.prototype.addChangeListener = function addChangeListener(listener) {
+ this.changeListeners.push(listener);
+ };
+
+ History.prototype.removeChangeListener = function removeChangeListener(listener) {
+ this.changeListeners = this.changeListeners.filter(function (li) {
+ return li !== listener;
+ });
+ };
+
+ History.prototype.back = function back() {
+ this.go(-1);
+ };
+
+ History.prototype.forward = function forward() {
+ this.go(1);
+ };
+
+ History.prototype._createState = function _createState(state) {
+ state = state || {};
+
+ if (!state.key) state.key = createRandomKey();
+
+ return state;
+ };
+
+ History.prototype.createLocation = function createLocation(path, state, navigationType) {
+ var pathname = (0, _URLUtils.getPathname)(path);
+ var queryString = (0, _URLUtils.getQueryString)(path);
+ var query = queryString ? this.parseQueryString(queryString) : null;
+ return new _Location2['default'](pathname, query, state, navigationType);
+ };
+
+ return History;
+ })();
+
+ exports['default'] = History;
+ module.exports = exports['default'];
+
+/***/ },
+/* 4 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule invariant
+ */
+
+ 'use strict';
+
+ /**
+ * Use invariant() to assert state which your program assumes to be true.
+ *
+ * Provide sprintf-style format (only %s is supported) and arguments
+ * to provide information about what broke and what you were
+ * expecting.
+ *
+ * The invariant message will be stripped in production, but the invariant
+ * will remain to ensure logic does not differ in production.
+ */
+
+ var __DEV__ = process.env.NODE_ENV !== 'production';
+
+ var invariant = function(condition, format, a, b, c, d, e, f) {
+ if (__DEV__) {
+ if (format === undefined) {
+ throw new Error('invariant requires an error message argument');
+ }
+ }
+
+ if (!condition) {
+ var error;
+ if (format === undefined) {
+ 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];
+ var argIndex = 0;
+ error = new Error(
+ 'Invariant Violation: ' +
+ format.replace(/%s/g, function() { return args[argIndex++]; })
+ );
+ }
+
+ error.framesToPop = 1; // we don't care about invariant's own frame
+ throw error;
+ }
+ };
+
+ module.exports = invariant;
+
+
+/***/ },
+/* 5 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports.stringifyQuery = stringifyQuery;
+ exports.getPathname = getPathname;
+ exports.getQueryString = getQueryString;
+ exports.stripLeadingSlashes = stripLeadingSlashes;
+ exports.isAbsolutePath = isAbsolutePath;
+ exports.compilePattern = compilePattern;
+ exports.matchPattern = matchPattern;
+ exports.getParamNames = getParamNames;
+ exports.formatPattern = formatPattern;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _qs = __webpack_require__(6);
+
+ var _qs2 = _interopRequireDefault(_qs);
+
+ var _invariant = __webpack_require__(4);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var parseQueryString = _qs2['default'].parse;
+
+ exports.parseQueryString = parseQueryString;
+
+ function stringifyQuery(query) {
+ return _qs2['default'].stringify(query, { arrayFormat: 'brackets' });
+ }
+
+ var queryMatcher = /\?(.*)$/;
+
+ function getPathname(path) {
+ return path.replace(queryMatcher, '');
+ }
+
+ function getQueryString(path) {
+ var match = path.match(queryMatcher);
+ return match ? match[1] : '';
+ }
+
+ function stripLeadingSlashes(path) {
+ return path ? path.replace(/^\/+/, '') : '';
+ }
+
+ function isAbsolutePath(path) {
+ return typeof path === 'string' && path.charAt(0) === '/';
+ }
+
+ function escapeRegExp(string) {
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ }
+
+ function escapeSource(string) {
+ return escapeRegExp(string).replace(/\/+/g, '/+');
+ }
+
+ function _compilePattern(pattern) {
+ var regexpSource = '';
+ var paramNames = [];
+ var tokens = [];
+
+ var match,
+ lastIndex = 0,
+ matcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|\*|\(|\)/g;
+ while (match = matcher.exec(pattern)) {
+ if (match.index !== lastIndex) {
+ tokens.push(pattern.slice(lastIndex, match.index));
+ regexpSource += escapeSource(pattern.slice(lastIndex, match.index));
+ }
+
+ if (match[1]) {
+ regexpSource += '([^/?#]+)';
+ paramNames.push(match[1]);
+ } else if (match[0] === '*') {
+ regexpSource += '(.*?)';
+ paramNames.push('splat');
+ } else if (match[0] === '(') {
+ regexpSource += '(?:';
+ } else if (match[0] === ')') {
+ regexpSource += ')?';
+ }
+
+ tokens.push(match[0]);
+
+ lastIndex = matcher.lastIndex;
+ }
+
+ if (lastIndex !== pattern.length) {
+ tokens.push(pattern.slice(lastIndex, pattern.length));
+ regexpSource += escapeSource(pattern.slice(lastIndex, pattern.length));
+ }
+
+ return {
+ pattern: pattern,
+ regexpSource: regexpSource,
+ paramNames: paramNames,
+ tokens: tokens
+ };
+ }
+
+ var CompiledPatternsCache = {};
+
+ function compilePattern(pattern) {
+ if (!(pattern in CompiledPatternsCache)) CompiledPatternsCache[pattern] = _compilePattern(pattern);
+
+ return CompiledPatternsCache[pattern];
+ }
+
+ /**
+ * Attempts to match a pattern on the given pathname. Patterns may use
+ * the following special characters:
+ *
+ * - :paramName Matches a URL segment up to the next /, ?, or #. The
+ * captured string is considered a "param"
+ * - () Wraps a segment of the URL that is optional
+ * - * Consumes (non-greedy) all characters up to the next
+ * character in the pattern, or to the end of the URL if
+ * there is none
+ *
+ * The return value is an object with the following properties:
+ *
+ * - remainingPathname
+ * - paramNames
+ * - paramValues
+ */
+
+ function matchPattern(pattern, pathname) {
+ var _compilePattern2 = compilePattern(stripLeadingSlashes(pattern));
+
+ var regexpSource = _compilePattern2.regexpSource;
+ var paramNames = _compilePattern2.paramNames;
+ var tokens = _compilePattern2.tokens;
+
+ regexpSource += '/*'; // Ignore trailing slashes
+
+ var captureRemaining = tokens[tokens.length - 1] !== '*';
+
+ if (captureRemaining) regexpSource += '(.*?)';
+
+ var match = pathname.match(new RegExp('^' + regexpSource + '$', 'i'));
+
+ var remainingPathname, paramValues;
+ if (match != null) {
+ paramValues = Array.prototype.slice.call(match, 1);
+
+ if (captureRemaining) {
+ remainingPathname = paramValues.pop();
+ } else {
+ remainingPathname = pathname.replace(match[0], '');
+ }
+ }
+
+ return {
+ remainingPathname: remainingPathname,
+ paramNames: paramNames,
+ paramValues: paramValues
+ };
+ }
+
+ function getParamNames(pattern) {
+ return compilePattern(pattern).paramNames;
+ }
+
+ /**
+ * Returns a version of the given pattern with params interpolated. Throws
+ * if there is a dynamic segment of the pattern for which there is no param.
+ */
+
+ function formatPattern(pattern, params) {
+ params = params || {};
+
+ var _compilePattern3 = compilePattern(pattern);
+
+ var tokens = _compilePattern3.tokens;
+
+ var parenCount = 0,
+ pathname = '',
+ splatIndex = 0;
+
+ var token, paramName, paramValue;
+ for (var i = 0, len = tokens.length; i < len; ++i) {
+ token = tokens[i];
+
+ if (token === '*') {
+ paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat;
+
+ (0, _invariant2['default'])(paramValue != null || parenCount > 0, 'Missing splat #%s for path "%s"', splatIndex, pattern);
+
+ if (paramValue != null) pathname += paramValue;
+ } else if (token === '(') {
+ parenCount += 1;
+ } else if (token === ')') {
+ parenCount -= 1;
+ } else if (token.charAt(0) === ':') {
+ paramName = token.substring(1);
+ paramValue = params[paramName];
+
+ (0, _invariant2['default'])(paramValue != null || parenCount > 0, 'Missing "%s" parameter for path "%s"', paramName, pattern);
+
+ if (paramValue != null) pathname += paramValue;
+ } else {
+ pathname += token;
+ }
+ }
+
+ return pathname.replace(/\/+/g, '/');
+ }
+
+/***/ },
+/* 6 */
+/***/ function(module, exports, __webpack_require__) {
+
+ module.exports = __webpack_require__(7);
+
+
+/***/ },
+/* 7 */
+/***/ function(module, exports, __webpack_require__) {
+
+ // Load modules
+
+ var Stringify = __webpack_require__(8);
+ var Parse = __webpack_require__(10);
+
+
+ // Declare internals
+
+ var internals = {};
+
+
+ module.exports = {
+ stringify: Stringify,
+ parse: Parse
+ };
+
+
+/***/ },
+/* 8 */
+/***/ function(module, exports, __webpack_require__) {
+
+ // Load modules
+
+ var Utils = __webpack_require__(9);
+
+
+ // Declare internals
+
+ var internals = {
+ delimiter: '&',
+ arrayPrefixGenerators: {
+ brackets: function (prefix, key) {
+ return prefix + '[]';
+ },
+ indices: function (prefix, key) {
+ return prefix + '[' + key + ']';
+ },
+ repeat: function (prefix, key) {
+ return prefix;
+ }
+ }
+ };
+
+
+ internals.stringify = function (obj, prefix, generateArrayPrefix) {
+
+ if (Utils.isBuffer(obj)) {
+ obj = obj.toString();
+ }
+ else if (obj instanceof Date) {
+ obj = obj.toISOString();
+ }
+ else if (obj === null) {
+ obj = '';
+ }
+
+ if (typeof obj === 'string' ||
+ typeof obj === 'number' ||
+ typeof obj === 'boolean') {
+
+ return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)];
+ }
+
+ var values = [];
+
+ if (typeof obj === 'undefined') {
+ return values;
+ }
+
+ var objKeys = Object.keys(obj);
+ for (var i = 0, il = objKeys.length; i < il; ++i) {
+ var key = objKeys[i];
+ if (Array.isArray(obj)) {
+ values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix));
+ }
+ else {
+ values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix));
+ }
+ }
+
+ return values;
+ };
+
+
+ module.exports = function (obj, options) {
+
+ options = options || {};
+ var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
+
+ var keys = [];
+
+ if (typeof obj !== 'object' ||
+ obj === null) {
+
+ return '';
+ }
+
+ var arrayFormat;
+ if (options.arrayFormat in internals.arrayPrefixGenerators) {
+ arrayFormat = options.arrayFormat;
+ }
+ else if ('indices' in options) {
+ arrayFormat = options.indices ? 'indices' : 'repeat';
+ }
+ else {
+ arrayFormat = 'indices';
+ }
+
+ var generateArrayPrefix = internals.arrayPrefixGenerators[arrayFormat];
+
+ var objKeys = Object.keys(obj);
+ for (var i = 0, il = objKeys.length; i < il; ++i) {
+ var key = objKeys[i];
+ keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix));
+ }
+
+ return keys.join(delimiter);
+ };
+
+
+/***/ },
+/* 9 */
+/***/ function(module, exports) {
+
+ // Load modules
+
+
+ // Declare internals
+
+ var internals = {};
+
+
+ exports.arrayToObject = function (source) {
+
+ var obj = {};
+ for (var i = 0, il = source.length; i < il; ++i) {
+ if (typeof source[i] !== 'undefined') {
+
+ obj[i] = source[i];
+ }
+ }
+
+ return obj;
+ };
+
+
+ exports.merge = function (target, source) {
+
+ if (!source) {
+ return target;
+ }
+
+ if (typeof source !== 'object') {
+ if (Array.isArray(target)) {
+ target.push(source);
+ }
+ else {
+ target[source] = true;
+ }
+
+ return target;
+ }
+
+ if (typeof target !== 'object') {
+ target = [target].concat(source);
+ return target;
+ }
+
+ if (Array.isArray(target) &&
+ !Array.isArray(source)) {
+
+ target = exports.arrayToObject(target);
+ }
+
+ var keys = Object.keys(source);
+ for (var k = 0, kl = keys.length; k < kl; ++k) {
+ var key = keys[k];
+ var value = source[key];
+
+ if (!target[key]) {
+ target[key] = value;
+ }
+ else {
+ target[key] = exports.merge(target[key], value);
+ }
+ }
+
+ return target;
+ };
+
+
+ exports.decode = function (str) {
+
+ try {
+ return decodeURIComponent(str.replace(/\+/g, ' '));
+ } catch (e) {
+ return str;
+ }
+ };
+
+
+ exports.compact = function (obj, refs) {
+
+ if (typeof obj !== 'object' ||
+ obj === null) {
+
+ return obj;
+ }
+
+ refs = refs || [];
+ var lookup = refs.indexOf(obj);
+ if (lookup !== -1) {
+ return refs[lookup];
+ }
+
+ refs.push(obj);
+
+ if (Array.isArray(obj)) {
+ var compacted = [];
+
+ for (var i = 0, il = obj.length; i < il; ++i) {
+ if (typeof obj[i] !== 'undefined') {
+ compacted.push(obj[i]);
+ }
+ }
+
+ return compacted;
+ }
+
+ var keys = Object.keys(obj);
+ for (i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ obj[key] = exports.compact(obj[key], refs);
+ }
+
+ return obj;
+ };
+
+
+ exports.isRegExp = function (obj) {
+ return Object.prototype.toString.call(obj) === '[object RegExp]';
+ };
+
+
+ exports.isBuffer = function (obj) {
+
+ if (obj === null ||
+ typeof obj === 'undefined') {
+
+ return false;
+ }
+
+ return !!(obj.constructor &&
+ obj.constructor.isBuffer &&
+ obj.constructor.isBuffer(obj));
+ };
+
+
+/***/ },
+/* 10 */
+/***/ function(module, exports, __webpack_require__) {
+
+ // Load modules
+
+ var Utils = __webpack_require__(9);
+
+
+ // Declare internals
+
+ var internals = {
+ delimiter: '&',
+ depth: 5,
+ arrayLimit: 20,
+ parameterLimit: 1000
+ };
+
+
+ internals.parseValues = function (str, options) {
+
+ var obj = {};
+ var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
+
+ for (var i = 0, il = parts.length; i < il; ++i) {
+ var part = parts[i];
+ var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
+
+ if (pos === -1) {
+ obj[Utils.decode(part)] = '';
+ }
+ else {
+ var key = Utils.decode(part.slice(0, pos));
+ var val = Utils.decode(part.slice(pos + 1));
+
+ if (Object.prototype.hasOwnProperty(key)) {
+ continue;
+ }
+
+ if (!obj.hasOwnProperty(key)) {
+ obj[key] = val;
+ }
+ else {
+ obj[key] = [].concat(obj[key]).concat(val);
+ }
+ }
+ }
+
+ return obj;
+ };
+
+
+ internals.parseObject = function (chain, val, options) {
+
+ if (!chain.length) {
+ return val;
+ }
+
+ var root = chain.shift();
+
+ var 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;
+ var index = parseInt(cleanRoot, 10);
+ var indexString = '' + index;
+ if (!isNaN(index) &&
+ root !== cleanRoot &&
+ indexString === cleanRoot &&
+ index >= 0 &&
+ index <= options.arrayLimit) {
+
+ obj = [];
+ obj[index] = internals.parseObject(chain, val, options);
+ }
+ else {
+ obj[cleanRoot] = internals.parseObject(chain, val, options);
+ }
+ }
+
+ return obj;
+ };
+
+
+ internals.parseKeys = function (key, val, options) {
+
+ if (!key) {
+ return;
+ }
+
+ // The regex chunks
+
+ var parent = /^([^\[\]]*)/;
+ var child = /(\[[^\[\]]*\])/g;
+
+ // Get the parent
+
+ var segment = parent.exec(key);
+
+ // Don't allow them to overwrite object prototype properties
+
+ if (Object.prototype.hasOwnProperty(segment[1])) {
+ return;
+ }
+
+ // Stash the parent if it exists
+
+ var keys = [];
+ if (segment[1]) {
+ keys.push(segment[1]);
+ }
+
+ // Loop through children appending to the array until we hit depth
+
+ var i = 0;
+ while ((segment = child.exec(key)) !== null && i < options.depth) {
+
+ ++i;
+ if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
+ keys.push(segment[1]);
+ }
+ }
+
+ // If there's a remainder, just add whatever is left
+
+ if (segment) {
+ keys.push('[' + key.slice(segment.index) + ']');
+ }
+
+ return internals.parseObject(keys, val, options);
+ };
+
+
+ module.exports = function (str, options) {
+
+ if (str === '' ||
+ str === null ||
+ typeof str === 'undefined') {
+
+ return {};
+ }
+
+ options = options || {};
+ options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
+ options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
+ options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
+ options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
+
+ var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str;
+ var obj = {};
+
+ // Iterate over the keys and setup the new object
+
+ var keys = Object.keys(tempObj);
+ for (var i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ var newObj = internals.parseKeys(key, tempObj[key], options);
+ obj = Utils.merge(obj, newObj);
+ }
+
+ return Utils.compact(obj);
+ };
+
+
+/***/ },
+/* 11 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ var _NavigationTypes = __webpack_require__(12);
+
+ var _NavigationTypes2 = _interopRequireDefault(_NavigationTypes);
+
+ /**
+ * A Location answers two important questions:
+ *
+ * 1. Where am I?
+ * 2. How did I get here?
+ */
+
+ var Location = (function () {
+ function Location() {
+ var pathname = arguments[0] === undefined ? '/' : arguments[0];
+ var query = arguments[1] === undefined ? null : arguments[1];
+ var state = arguments[2] === undefined ? null : arguments[2];
+ var navigationType = arguments[3] === undefined ? _NavigationTypes2['default'].POP : arguments[3];
+
+ _classCallCheck(this, Location);
+
+ this.pathname = pathname;
+ this.query = query;
+ this.state = state;
+ this.navigationType = navigationType;
+ }
+
+ Location.isLocation = function isLocation(object) {
+ return object instanceof Location;
+ };
+
+ return Location;
+ })();
+
+ exports['default'] = Location;
+ module.exports = exports['default'];
+
+/***/ },
+/* 12 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _keymirror = __webpack_require__(13);
+
+ var _keymirror2 = _interopRequireDefault(_keymirror);
+
+ var NavigationTypes = (0, _keymirror2['default'])({
+
+ /**
+ * Indicates that navigation was caused by a call to history.push.
+ */
+ PUSH: null,
+
+ /**
+ * Indicates that navigation was caused by a call to history.replace.
+ */
+ REPLACE: null,
+
+ /**
+ * Indicates that navigation was caused by some other action such
+ * as using a browser's back/forward buttons and/or manually manipulating
+ * the URL in a browser's location bar. This is the default.
+ *
+ * See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
+ * for more information.
+ */
+ POP: null
+
+ });
+
+ exports['default'] = NavigationTypes;
+ module.exports = exports['default'];
+
+/***/ },
+/* 13 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2014 Facebook, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+ "use strict";
+
+ /**
+ * Constructs an enumeration with keys equal to their value.
+ *
+ * For example:
+ *
+ * var COLORS = keyMirror({blue: null, red: null});
+ * var myColor = COLORS.blue;
+ * var isColorValid = !!COLORS[myColor];
+ *
+ * The last line could not be performed if the values of the generated enum were
+ * not equal to their keys.
+ *
+ * Input: {key1: val1, key2: val2}
+ * Output: {key1: key1, key2: key2}
+ *
+ * @param {object} obj
+ * @return {object}
+ */
+ var keyMirror = function(obj) {
+ var ret = {};
+ var key;
+ if (!(obj instanceof Object && !Array.isArray(obj))) {
+ throw new Error('keyMirror(...): Argument must be an object.');
+ }
+ for (key in obj) {
+ if (!obj.hasOwnProperty(key)) {
+ continue;
+ }
+ ret[key] = key;
+ }
+ return ret;
+ };
+
+ module.exports = keyMirror;
+
+
+/***/ },
+/* 14 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports.getHashPath = getHashPath;
+ exports.replaceHashPath = replaceHashPath;
+ exports.getWindowPath = getWindowPath;
+ exports.getWindowScrollPosition = getWindowScrollPosition;
+ exports.setWindowScrollPosition = setWindowScrollPosition;
+ exports.supportsHistory = supportsHistory;
+ var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
+
+ exports.canUseDOM = canUseDOM;
+
+ function getHashPath() {
+ return decodeURI(
+ // We can't use window.location.hash here because it's not
+ // consistent across browsers - Firefox will pre-decode it!
+ window.location.href.split('#')[1] || '');
+ }
+
+ function replaceHashPath(path) {
+ window.location.replace(window.location.pathname + window.location.search + '#' + path);
+ }
+
+ function getWindowPath() {
+ return decodeURI(window.location.pathname + window.location.search);
+ }
+
+ function getWindowScrollPosition() {
+ return {
+ scrollX: window.pageXOffset || document.documentElement.scrollLeft,
+ scrollY: window.pageYOffset || document.documentElement.scrollTop
+ };
+ }
+
+ function setWindowScrollPosition(scrollX, scrollY) {
+ window.scrollTo(scrollX, scrollY);
+ }
+
+ /**
+ * taken from modernizr
+ * https://github.com/Modernizr/Modernizr/blob/master/LICENSE
+ * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
+ * changed to avoid false negatives for Windows Phones: https://github.com/rackt/react-router/issues/586
+ */
+
+ function supportsHistory() {
+ var ua = navigator.userAgent;
+ if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) {
+ return false;
+ }
+ return window.history && 'pushState' in window.history;
+ }
+
+/***/ },
+/* 15 */
+/***/ function(module, exports, __webpack_require__) {
+
+
+ /**
+ * Module dependencies.
+ */
+
+ var tty = __webpack_require__(16);
+ var util = __webpack_require__(17);
+
+ /**
+ * This is the Node.js implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+ exports = module.exports = __webpack_require__(18);
+ exports.log = log;
+ exports.formatArgs = formatArgs;
+ exports.save = save;
+ exports.load = load;
+ exports.useColors = useColors;
+
+ /**
+ * Colors.
+ */
+
+ exports.colors = [6, 2, 3, 4, 5, 1];
+
+ /**
+ * The file descriptor to write the `debug()` calls to.
+ * Set the `DEBUG_FD` env variable to override with another value. i.e.:
+ *
+ * $ DEBUG_FD=3 node script.js 3>debug.log
+ */
+
+ var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
+ var stream = 1 === fd ? process.stdout :
+ 2 === fd ? process.stderr :
+ createWritableStdioStream(fd);
+
+ /**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
+
+ function useColors() {
+ var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
+ if (0 === debugColors.length) {
+ return tty.isatty(fd);
+ } else {
+ return '0' !== debugColors
+ && 'no' !== debugColors
+ && 'false' !== debugColors
+ && 'disabled' !== debugColors;
+ }
+ }
+
+ /**
+ * Map %o to `util.inspect()`, since Node doesn't do that out of the box.
+ */
+
+ var inspect = (4 === util.inspect.length ?
+ // node <= 0.8.x
+ function (v, colors) {
+ return util.inspect(v, void 0, void 0, colors);
+ } :
+ // node > 0.8.x
+ function (v, colors) {
+ return util.inspect(v, { colors: colors });
+ }
+ );
+
+ exports.formatters.o = function(v) {
+ return inspect(v, this.useColors)
+ .replace(/\s*\n\s*/g, ' ');
+ };
+
+ /**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
+
+ function formatArgs() {
+ var args = arguments;
+ var useColors = this.useColors;
+ var name = this.namespace;
+
+ if (useColors) {
+ var c = this.color;
+
+ args[0] = ' \u001b[3' + c + ';1m' + name + ' '
+ + '\u001b[0m'
+ + args[0] + '\u001b[3' + c + 'm'
+ + ' +' + exports.humanize(this.diff) + '\u001b[0m';
+ } else {
+ args[0] = new Date().toUTCString()
+ + ' ' + name + ' ' + args[0];
+ }
+ return args;
+ }
+
+ /**
+ * Invokes `console.error()` with the specified arguments.
+ */
+
+ function log() {
+ return stream.write(util.format.apply(this, arguments) + '\n');
+ }
+
+ /**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+ function save(namespaces) {
+ if (null == namespaces) {
+ // If you set a process.env field to null or undefined, it gets cast to the
+ // string 'null' or 'undefined'. Just delete instead.
+ delete process.env.DEBUG;
+ } else {
+ process.env.DEBUG = namespaces;
+ }
+ }
+
+ /**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+ function load() {
+ return process.env.DEBUG;
+ }
+
+ /**
+ * Copied from `node/src/node.js`.
+ *
+ * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
+ * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
+ */
+
+ function createWritableStdioStream (fd) {
+ var stream;
+ var tty_wrap = process.binding('tty_wrap');
+
+ // Note stream._type is used for test-module-load-list.js
+
+ switch (tty_wrap.guessHandleType(fd)) {
+ case 'TTY':
+ stream = new tty.WriteStream(fd);
+ stream._type = 'tty';
+
+ // Hack to have stream not keep the event loop alive.
+ // See https://github.com/joyent/node/issues/1726
+ if (stream._handle && stream._handle.unref) {
+ stream._handle.unref();
+ }
+ break;
+
+ case 'FILE':
+ var fs = __webpack_require__(20);
+ stream = new fs.SyncWriteStream(fd, { autoClose: false });
+ stream._type = 'fs';
+ break;
+
+ case 'PIPE':
+ case 'TCP':
+ var net = __webpack_require__(21);
+ stream = new net.Socket({
+ fd: fd,
+ readable: false,
+ writable: true
+ });
+
+ // FIXME Should probably have an option in net.Socket to create a
+ // stream from an existing fd which is writable only. But for now
+ // we'll just add this hack and set the `readable` member to false.
+ // Test: ./node test/fixtures/echo.js < /etc/passwd
+ stream.readable = false;
+ stream.read = null;
+ stream._type = 'pipe';
+
+ // FIXME Hack to have stream not keep the event loop alive.
+ // See https://github.com/joyent/node/issues/1726
+ if (stream._handle && stream._handle.unref) {
+ stream._handle.unref();
+ }
+ break;
+
+ default:
+ // Probably an error on in uv_guess_handle()
+ throw new Error('Implement me. Unknown stream file type!');
+ }
+
+ // For supporting legacy API we put the FD here.
+ stream.fd = fd;
+
+ stream._isStdio = true;
+
+ return stream;
+ }
+
+ /**
+ * Enable namespaces listed in `process.env.DEBUG` initially.
+ */
+
+ exports.enable(load());
+
+
+/***/ },
+/* 16 */
+/***/ function(module, exports) {
+
+ module.exports = require("tty");
+
+/***/ },
+/* 17 */
+/***/ function(module, exports) {
+
+ module.exports = require("util");
+
+/***/ },
+/* 18 */
+/***/ function(module, exports, __webpack_require__) {
+
+
+ /**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+ exports = module.exports = debug;
+ exports.coerce = coerce;
+ exports.disable = disable;
+ exports.enable = enable;
+ exports.enabled = enabled;
+ exports.humanize = __webpack_require__(19);
+
+ /**
+ * 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, lowercased letter, i.e. "n".
+ */
+
+ exports.formatters = {};
+
+ /**
+ * Previously assigned color.
+ */
+
+ var prevColor = 0;
+
+ /**
+ * Previous log timestamp.
+ */
+
+ var prevTime;
+
+ /**
+ * Select a color.
+ *
+ * @return {Number}
+ * @api private
+ */
+
+ function selectColor() {
+ return exports.colors[prevColor++ % exports.colors.length];
+ }
+
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+ function debug(namespace) {
+
+ // define the `disabled` version
+ function disabled() {
+ }
+ disabled.enabled = false;
+
+ // define the `enabled` version
+ function enabled() {
+
+ var self = enabled;
+
+ // set `diff` timestamp
+ var curr = +new Date();
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ // add the `color` if not set
+ if (null == self.useColors) self.useColors = exports.useColors();
+ if (null == self.color && self.useColors) self.color = selectColor();
+
+ var args = Array.prototype.slice.call(arguments);
+
+ args[0] = exports.coerce(args[0]);
+
+ if ('string' !== typeof args[0]) {
+ // anything else let's inspect with %o
+ args = ['%o'].concat(args);
+ }
+
+ // apply any `formatters` transformations
+ var index = 0;
+ args[0] = args[0].replace(/%([a-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;
+ });
+
+ if ('function' === typeof exports.formatArgs) {
+ args = exports.formatArgs.apply(self, args);
+ }
+ var logFn = enabled.log || exports.log || console.log.bind(console);
+ logFn.apply(self, args);
+ }
+ enabled.enabled = true;
+
+ var fn = exports.enabled(namespace) ? enabled : disabled;
+
+ fn.namespace = namespace;
+
+ return fn;
+ }
+
+ /**
+ * 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);
+
+ var split = (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;
+ }
+
+
+/***/ },
+/* 19 */
+/***/ function(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
+ * @return {String|Number}
+ * @api public
+ */
+
+ module.exports = function(val, options){
+ options = options || {};
+ if ('string' == typeof val) return parse(val);
+ return options.long
+ ? long(val)
+ : short(val);
+ };
+
+ /**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+ function parse(str) {
+ 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;
+ }
+ }
+
+ /**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+ function short(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 long(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';
+ }
+
+
+/***/ },
+/* 20 */
+/***/ function(module, exports) {
+
+ module.exports = require("fs");
+
+/***/ },
+/* 21 */
+/***/ function(module, exports) {
+
+ module.exports = require("net");
+
+/***/ },
+/* 22 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _Actions = __webpack_require__(23);
+
+ var _Actions2 = _interopRequireDefault(_Actions);
+
+ var _Cat = __webpack_require__(47);
+
+ var _Cat2 = _interopRequireDefault(_Cat);
+
+ var _Store = __webpack_require__(49);
+
+ var _Store2 = _interopRequireDefault(_Store);
+
+ var _createContainer = __webpack_require__(212);
+
+ var _createContainer2 = _interopRequireDefault(_createContainer);
+
+ var _waitFor = __webpack_require__(45);
+
+ var _waitFor2 = _interopRequireDefault(_waitFor);
+
+ exports['default'] = {
+ Actions: _Actions2['default'],
+ Cat: _Cat2['default'],
+ createContainer: _createContainer2['default'],
+ Store: _Store2['default'],
+ waitFor: _waitFor2['default']
+ };
+ module.exports = exports['default'];
+
+/***/ },
+/* 23 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+ exports.getActionNames = getActionNames;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _invariant = __webpack_require__(38);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var _objectAssign = __webpack_require__(39);
+
+ var _objectAssign2 = _interopRequireDefault(_objectAssign);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _waitFor = __webpack_require__(45);
+
+ var _waitFor2 = _interopRequireDefault(_waitFor);
+
+ var debug = (0, _debug2['default'])('thundercats:actions');
+ var protectedProperties = ['displayName', 'constructor'];
+
+ function getActionNames(ctx) {
+ return Object.getOwnPropertyNames(ctx.constructor.prototype).filter(function (name) {
+ return protectedProperties.indexOf(name) === -1 && name.indexOf('_') === -1 && typeof ctx[name] === 'function';
+ });
+ }
+
+ var ActionCreator = {
+ create: function create(name, map) {
+ var observers = [];
+ var actionStart = new _rx2['default'].Subject();
+
+ function action(value) {
+ value = map(value);
+
+ actionStart.onNext(value);
+ observers.forEach(function (observer) {
+ observer.onNext(value);
+ });
+
+ return value;
+ }
+
+ action.displayName = name;
+ action.observers = observers;
+ (0, _objectAssign2['default'])(action, _rx2['default'].Observable.prototype, _rx2['default'].Subject.prototype);
+
+ action.hasObservers = function hasObservers() {
+ return observers.length > 0 || actionStart.hasObservers();
+ };
+
+ action.waitFor = function () {
+ var _arguments = arguments;
+
+ return actionStart.flatMap(function (payload) {
+ return _waitFor2['default'].apply(undefined, _arguments).map(function () {
+ return payload;
+ });
+ });
+ };
+
+ _rx2['default'].Observable.call(action, function (observer) {
+ observers.push(observer);
+ return new _rx2['default'].Disposable(function () {
+ observers.splice(observers.indexOf(observer), 1);
+ });
+ });
+
+ debug('action %s created', action.displayName);
+ return action;
+ },
+
+ createManyOn: function createManyOn(ctx, actions) {
+ (0, _invariant2['default'])(Array.isArray(actions), 'createActions requires an array but got %s', actions);
+
+ var actionsBag = actions.reduce(function (ctx, action) {
+ (0, _invariant2['default'])(action && typeof action === 'object', 'createActions requires items in array to be objects but ' + 'was supplied with %s', action);
+
+ (0, _invariant2['default'])(typeof action.name === 'string', 'createActions requires objects to have a name key, but got %s', action.name);
+
+ /* istanbul ignore else */
+ if (action.map) {
+ (0, _invariant2['default'])(typeof action.map === 'function', 'createActions requires objects with map field to be a function ' + 'but was given %s', action.map);
+ }
+
+ ctx[action.name] = ActionCreator.create(action.name, action.map);
+ return ctx;
+ }, {});
+
+ return (0, _objectAssign2['default'])(ctx, actionsBag);
+ }
+ };
+
+ exports.ActionCreator = ActionCreator;
+
+ var Actions = function Actions(actionNames) {
+ var _this = this;
+
+ _classCallCheck(this, Actions);
+
+ if (actionNames) {
+ (0, _invariant2['default'])(Array.isArray(actionNames) && actionNames.every(function (actionName) {
+ return typeof actionName === 'string';
+ }), '%s should get an array of strings but got %s', actionNames);
+ }
+
+ var actionDefinitions = getActionNames(this).map(function (name) {
+ return { name: name, map: _this[name] };
+ });
+
+ if (actionNames) {
+ actionDefinitions = actionDefinitions.concat(actionNames.map(function (name) {
+ return { name: name, map: _rx2['default'].helpers.identity };
+ }));
+ }
+
+ // istanbul ignore else
+ if (actionDefinitions && actionDefinitions.length) {
+ ActionCreator.createManyOn(this, actionDefinitions);
+ }
+ };
+
+ exports['default'] = Actions;
+
+/***/ },
+/* 24 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var Rx = __webpack_require__(27);
+ __webpack_require__(28);
+ __webpack_require__(29);
+ __webpack_require__(30);
+ __webpack_require__(31);
+ __webpack_require__(32);
+ __webpack_require__(25);
+ __webpack_require__(33);
+ __webpack_require__(34);
+ __webpack_require__(35);
+ __webpack_require__(36);
+ __webpack_require__(37);
+
+ module.exports = Rx;
+
+
+/***/ },
+/* 25 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // Aliases
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ observableConcat = Observable.concat,
+ observableDefer = Observable.defer,
+ observableEmpty = Observable.empty,
+ disposableEmpty = Rx.Disposable.empty,
+ CompositeDisposable = Rx.CompositeDisposable,
+ SerialDisposable = Rx.SerialDisposable,
+ SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
+ Enumerator = Rx.internals.Enumerator,
+ Enumerable = Rx.internals.Enumerable,
+ enumerableOf = Enumerable.of,
+ immediateScheduler = Rx.Scheduler.immediate,
+ currentThreadScheduler = Rx.Scheduler.currentThread,
+ slice = Array.prototype.slice,
+ AsyncSubject = Rx.AsyncSubject,
+ Observer = Rx.Observer,
+ inherits = Rx.internals.inherits,
+ bindCallback = Rx.internals.bindCallback,
+ addProperties = Rx.internals.addProperties,
+ helpers = Rx.helpers,
+ noop = helpers.noop,
+ isPromise = helpers.isPromise,
+ isScheduler = Rx.Scheduler.isScheduler,
+ observableFromPromise = Observable.fromPromise;
+
+ // Shim in iterator support
+ var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
+ '_es6shim_iterator_';
+ // Bug for mozilla version
+ if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
+ $iterator$ = '@@iterator';
+ }
+
+ var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
+
+ var isIterable = Rx.helpers.isIterable = function (o) {
+ return o[$iterator$] !== undefined;
+ }
+
+ var isArrayLike = Rx.helpers.isArrayLike = function (o) {
+ return o && o.length !== undefined;
+ }
+
+ Rx.helpers.iterator = $iterator$;
+
+ var WhileEnumerable = (function(__super__) {
+ inherits(WhileEnumerable, __super__);
+ function WhileEnumerable(c, s) {
+ this.c = c;
+ this.s = s;
+ }
+ WhileEnumerable.prototype[$iterator$] = function () {
+ var self = this;
+ return {
+ next: function () {
+ return self.c() ?
+ { done: false, value: self.s } :
+ { done: true, value: void 0 };
+ }
+ };
+ };
+ return WhileEnumerable;
+ }(Enumerable));
+
+ function enumerableWhile(condition, source) {
+ return new WhileEnumerable(condition, source);
+ }
+
+ /**
+ * 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 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;
+ }, this);
+ };
+
+ /**
+ * 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 = [];
+ if (Array.isArray(arguments[0])) {
+ allSources = arguments[0];
+ } else {
+ for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
+ }
+ 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);
+ }, first);
+ };
+
+ /**
+ * 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 = observableProto.extend = 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);
+ }, source);
+ };
+
+ 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.mergeAll().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.throwError(e));
+ },
+ onNext: function (v) {
+ this.tail.onNext(v);
+ this.tail.onCompleted();
+ }
+ });
+
+ return ChainObservable;
+
+ }(Observable));
+
+ /*
+ * 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;
+ }, this);
+ };
+
+ /*
+ * 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,
+ selectorFunc = bindCallback(selector, thisArg, 3);
+ 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 = selectorFunc(x, index++, innerSource);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+
+ observer.onNext(result);
+ },
+ function (e) { observer.onError(e); },
+ function () {
+ g.remove(innerSubscription);
+ hasCurrent = false;
+
+ if (isStopped && g.length === 1) {
+ observer.onCompleted();
+ }
+ }));
+ }
+ },
+ function (e) { observer.onError(e); },
+ function () {
+ isStopped = true;
+ if (g.length === 1 && !hasCurrent) {
+ observer.onCompleted();
+ }
+ }));
+ return g;
+ }, this);
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 26 */
+/***/ function(module, exports) {
+
+ module.exports = function(module) {
+ if(!module.webpackPolyfill) {
+ module.deprecate = function() {};
+ module.paths = [];
+ // module.parent = undefined by default
+ module.children = [];
+ module.webpackPolyfill = 1;
+ }
+ return module;
+ }
+
+
+/***/ },
+/* 27 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (undefined) {
+
+ var objectTypes = {
+ 'boolean': false,
+ 'function': true,
+ 'object': true,
+ 'number': false,
+ 'string': false,
+ 'undefined': false
+ };
+
+ var root = (objectTypes[typeof window] && window) || this,
+ freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
+ freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
+ moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
+ freeGlobal = objectTypes[typeof global] && global;
+
+ if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
+ root = freeGlobal;
+ }
+
+ var Rx = {
+ internals: {},
+ config: {
+ Promise: root.Promise
+ },
+ helpers: { }
+ };
+
+ // Defaults
+ var noop = Rx.helpers.noop = function () { },
+ notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
+ 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.subscribe !== 'function' && typeof p.then === 'function'; },
+ asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
+ not = Rx.helpers.not = function (a) { return !a; },
+ isFunction = Rx.helpers.isFunction = (function () {
+
+ var isFn = function (value) {
+ return typeof value == 'function' || false;
+ }
+
+ // fallback for older versions of Chrome and Safari
+ if (isFn(/x/)) {
+ isFn = function(value) {
+ return typeof value == 'function' && toString.call(value) == '[object Function]';
+ };
+ }
+
+ return isFn;
+ }());
+
+ function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
+
+ Rx.config.longStackSupport = false;
+ var hasStacks = false;
+ try {
+ throw new Error();
+ } catch (e) {
+ hasStacks = !!e.stack;
+ }
+
+ // All code after this point will be filtered from stack traces reported by RxJS
+ var rStartingLine = captureLine(), rFileName;
+
+ var STACK_JUMP_SEPARATOR = "From previous event:";
+
+ function makeStackTraceLong(error, observable) {
+ // If possible, transform the error stack trace by removing Node and RxJS
+ // cruft, then concatenating with the stack trace of `observable`.
+ if (hasStacks &&
+ observable.stack &&
+ typeof error === "object" &&
+ error !== null &&
+ error.stack &&
+ error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
+ ) {
+ var stacks = [];
+ for (var o = observable; !!o; o = o.source) {
+ if (o.stack) {
+ stacks.unshift(o.stack);
+ }
+ }
+ stacks.unshift(error.stack);
+
+ var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
+ error.stack = filterStackString(concatedStacks);
+ }
+ }
+
+ function filterStackString(stackString) {
+ var lines = stackString.split("\n"),
+ desiredLines = [];
+ for (var i = 0, len = lines.length; i < len; i++) {
+ var line = lines[i];
+
+ if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
+ desiredLines.push(line);
+ }
+ }
+ return desiredLines.join("\n");
+ }
+
+ function isInternalFrame(stackLine) {
+ var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
+ if (!fileNameAndLineNumber) {
+ return false;
+ }
+ var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
+
+ return fileName === rFileName &&
+ lineNumber >= rStartingLine &&
+ lineNumber <= rEndingLine;
+ }
+
+ function isNodeFrame(stackLine) {
+ return stackLine.indexOf("(module.js:") !== -1 ||
+ stackLine.indexOf("(node.js:") !== -1;
+ }
+
+ function captureLine() {
+ if (!hasStacks) { return; }
+
+ try {
+ throw new Error();
+ } catch (e) {
+ var lines = e.stack.split("\n");
+ var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
+ var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
+ if (!fileNameAndLineNumber) { return; }
+
+ rFileName = fileNameAndLineNumber[0];
+ return fileNameAndLineNumber[1];
+ }
+ }
+
+ function getFileNameAndLineNumber(stackLine) {
+ // Named functions: "at functionName (filename:lineNumber:columnNumber)"
+ var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
+ if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
+
+ // Anonymous functions: "at filename:lineNumber:columnNumber"
+ var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
+ if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
+
+ // Firefox style: "function@filename:lineNumber or @filename:lineNumber"
+ var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
+ if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
+ }
+
+ var EmptyError = Rx.EmptyError = function() {
+ this.message = 'Sequence contains no elements.';
+ Error.call(this);
+ };
+ EmptyError.prototype = Error.prototype;
+
+ var ObjectDisposedError = Rx.ObjectDisposedError = function() {
+ this.message = 'Object has been disposed';
+ Error.call(this);
+ };
+ ObjectDisposedError.prototype = Error.prototype;
+
+ var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
+ this.message = 'Argument out of range';
+ Error.call(this);
+ };
+ ArgumentOutOfRangeError.prototype = Error.prototype;
+
+ var NotSupportedError = Rx.NotSupportedError = function (message) {
+ this.message = message || 'This operation is not supported';
+ Error.call(this);
+ };
+ NotSupportedError.prototype = Error.prototype;
+
+ var NotImplementedError = Rx.NotImplementedError = function (message) {
+ this.message = message || 'This operation is not implemented';
+ Error.call(this);
+ };
+ NotImplementedError.prototype = Error.prototype;
+
+ var notImplemented = Rx.helpers.notImplemented = function () {
+ throw new NotImplementedError();
+ };
+
+ var notSupported = Rx.helpers.notSupported = function () {
+ throw new NotSupportedError();
+ };
+
+ // Shim in iterator support
+ var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
+ '_es6shim_iterator_';
+ // Bug for mozilla version
+ if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
+ $iterator$ = '@@iterator';
+ }
+
+ var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
+
+ var isIterable = Rx.helpers.isIterable = function (o) {
+ return o[$iterator$] !== undefined;
+ }
+
+ var isArrayLike = Rx.helpers.isArrayLike = function (o) {
+ return o && o.length !== undefined;
+ }
+
+ Rx.helpers.iterator = $iterator$;
+
+ var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
+ if (typeof thisArg === 'undefined') { return func; }
+ switch(argCount) {
+ case 0:
+ return function() {
+ return func.call(thisArg)
+ };
+ case 1:
+ return function(arg) {
+ return func.call(thisArg, arg);
+ }
+ case 2:
+ return function(value, index) {
+ return func.call(thisArg, value, index);
+ };
+ case 3:
+ return function(value, index, collection) {
+ return func.call(thisArg, value, index, collection);
+ };
+ }
+
+ return function() {
+ return func.apply(thisArg, arguments);
+ };
+ };
+
+ /** Used to determine if values are of the language type Object */
+ var dontEnums = ['toString',
+ 'toLocaleString',
+ 'valueOf',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'constructor'],
+ dontEnumsLength = dontEnums.length;
+
+ /** `Object#toString` result shortcuts */
+ var argsClass = '[object Arguments]',
+ arrayClass = '[object Array]',
+ boolClass = '[object Boolean]',
+ dateClass = '[object Date]',
+ errorClass = '[object Error]',
+ funcClass = '[object Function]',
+ numberClass = '[object Number]',
+ objectClass = '[object Object]',
+ regexpClass = '[object RegExp]',
+ stringClass = '[object String]';
+
+ var toString = Object.prototype.toString,
+ hasOwnProperty = Object.prototype.hasOwnProperty,
+ supportsArgsClass = toString.call(arguments) == argsClass, // For less -1);
+ }
+ });
+ }
+ }
+ stackA.pop();
+ stackB.pop();
+
+ return result;
+ }
+
+ var hasProp = {}.hasOwnProperty,
+ slice = Array.prototype.slice;
+
+ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
+ function __() { this.constructor = child; }
+ __.prototype = parent.prototype;
+ child.prototype = new __();
+ };
+
+ var addProperties = Rx.internals.addProperties = function (obj) {
+ for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
+ for (var idx = 0, ln = sources.length; idx < ln; idx++) {
+ var source = sources[idx];
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ };
+
+ // Rx Utils
+ var addRef = Rx.internals.addRef = function (xs, r) {
+ return new AnonymousObservable(function (observer) {
+ return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
+ });
+ };
+
+ function arrayInitialize(count, factory) {
+ var a = new Array(count);
+ for (var i = 0; i < count; i++) {
+ a[i] = factory();
+ }
+ return a;
+ }
+
+ var errorObj = {e: {}};
+ var tryCatchTarget;
+ function tryCatcher() {
+ try {
+ return tryCatchTarget.apply(this, arguments);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+ }
+ function tryCatch(fn) {
+ if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
+ tryCatchTarget = fn;
+ return tryCatcher;
+ }
+ function thrower(e) {
+ throw e;
+ }
+
+ // Collections
+ function IndexedItem(id, value) {
+ this.id = id;
+ this.value = value;
+ }
+
+ IndexedItem.prototype.compareTo = function (other) {
+ var c = this.value.compareTo(other.value);
+ c === 0 && (c = this.id - other.id);
+ return c;
+ };
+
+ // Priority Queue for Scheduling
+ var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
+ this.items = new Array(capacity);
+ this.length = 0;
+ };
+
+ var priorityProto = PriorityQueue.prototype;
+ priorityProto.isHigherPriority = function (left, right) {
+ return this.items[left].compareTo(this.items[right]) < 0;
+ };
+
+ priorityProto.percolate = function (index) {
+ if (index >= this.length || index < 0) { return; }
+ var parent = index - 1 >> 1;
+ if (parent < 0 || parent === index) { return; }
+ if (this.isHigherPriority(index, parent)) {
+ var temp = this.items[index];
+ this.items[index] = this.items[parent];
+ this.items[parent] = temp;
+ this.percolate(parent);
+ }
+ };
+
+ priorityProto.heapify = function (index) {
+ +index || (index = 0);
+ if (index >= this.length || index < 0) { return; }
+ var left = 2 * index + 1,
+ right = 2 * index + 2,
+ first = index;
+ if (left < this.length && this.isHigherPriority(left, first)) {
+ first = left;
+ }
+ if (right < this.length && this.isHigherPriority(right, first)) {
+ first = right;
+ }
+ if (first !== index) {
+ var temp = this.items[index];
+ this.items[index] = this.items[first];
+ this.items[first] = temp;
+ this.heapify(first);
+ }
+ };
+
+ priorityProto.peek = function () { return this.items[0].value; };
+
+ priorityProto.removeAt = function (index) {
+ this.items[index] = this.items[--this.length];
+ this.items[this.length] = undefined;
+ this.heapify();
+ };
+
+ priorityProto.dequeue = function () {
+ var result = this.peek();
+ this.removeAt(0);
+ return result;
+ };
+
+ priorityProto.enqueue = function (item) {
+ var index = this.length++;
+ this.items[index] = new IndexedItem(PriorityQueue.count++, item);
+ this.percolate(index);
+ };
+
+ priorityProto.remove = function (item) {
+ for (var i = 0; i < this.length; i++) {
+ if (this.items[i].value === item) {
+ this.removeAt(i);
+ return true;
+ }
+ }
+ return false;
+ };
+ PriorityQueue.count = 0;
+
+ /**
+ * Represents a group of disposable resources that are disposed together.
+ * @constructor
+ */
+ var CompositeDisposable = Rx.CompositeDisposable = function () {
+ var args = [], i, len;
+ if (Array.isArray(arguments[0])) {
+ args = arguments[0];
+ len = args.length;
+ } else {
+ len = arguments.length;
+ args = new Array(len);
+ for(i = 0; i < len; i++) { args[i] = arguments[i]; }
+ }
+ for(i = 0; i < len; i++) {
+ if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
+ }
+ this.disposables = args;
+ this.isDisposed = false;
+ this.length = args.length;
+ };
+
+ var CompositeDisposablePrototype = CompositeDisposable.prototype;
+
+ /**
+ * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
+ * @param {Mixed} item Disposable to add.
+ */
+ CompositeDisposablePrototype.add = function (item) {
+ if (this.isDisposed) {
+ item.dispose();
+ } else {
+ this.disposables.push(item);
+ this.length++;
+ }
+ };
+
+ /**
+ * Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
+ * @param {Mixed} item Disposable to remove.
+ * @returns {Boolean} true if found; false otherwise.
+ */
+ CompositeDisposablePrototype.remove = function (item) {
+ var shouldDispose = false;
+ if (!this.isDisposed) {
+ var idx = this.disposables.indexOf(item);
+ if (idx !== -1) {
+ shouldDispose = true;
+ this.disposables.splice(idx, 1);
+ this.length--;
+ item.dispose();
+ }
+ }
+ return shouldDispose;
+ };
+
+ /**
+ * Disposes all disposables in the group and removes them from the group.
+ */
+ CompositeDisposablePrototype.dispose = function () {
+ if (!this.isDisposed) {
+ this.isDisposed = true;
+ var len = this.disposables.length, currentDisposables = new Array(len);
+ for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
+ this.disposables = [];
+ this.length = 0;
+
+ for (i = 0; i < len; i++) {
+ currentDisposables[i].dispose();
+ }
+ }
+ };
+
+ /**
+ * Provides a set of static methods for creating Disposables.
+ * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
+ */
+ var Disposable = Rx.Disposable = function (action) {
+ this.isDisposed = false;
+ this.action = action || noop;
+ };
+
+ /** Performs the task of cleaning up resources. */
+ Disposable.prototype.dispose = function () {
+ if (!this.isDisposed) {
+ this.action();
+ this.isDisposed = true;
+ }
+ };
+
+ /**
+ * Creates a disposable object that invokes the specified action when disposed.
+ * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
+ * @return {Disposable} The disposable object that runs the given action upon disposal.
+ */
+ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
+
+ /**
+ * Gets the disposable that does nothing when disposed.
+ */
+ var disposableEmpty = Disposable.empty = { dispose: noop };
+
+ /**
+ * Validates whether the given object is a disposable
+ * @param {Object} Object to test whether it has a dispose method
+ * @returns {Boolean} true if a disposable object, else false.
+ */
+ var isDisposable = Disposable.isDisposable = function (d) {
+ return d && isFunction(d.dispose);
+ };
+
+ var checkDisposed = Disposable.checkDisposed = function (disposable) {
+ if (disposable.isDisposed) { throw new ObjectDisposedError(); }
+ };
+
+ // Single assignment
+ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
+ this.isDisposed = false;
+ this.current = null;
+ };
+ SingleAssignmentDisposable.prototype.getDisposable = function () {
+ return this.current;
+ };
+ SingleAssignmentDisposable.prototype.setDisposable = function (value) {
+ if (this.current) { throw new Error('Disposable has already been assigned'); }
+ var shouldDispose = this.isDisposed;
+ !shouldDispose && (this.current = value);
+ shouldDispose && value && value.dispose();
+ };
+ SingleAssignmentDisposable.prototype.dispose = function () {
+ if (!this.isDisposed) {
+ this.isDisposed = true;
+ var old = this.current;
+ this.current = null;
+ }
+ old && old.dispose();
+ };
+
+ // Multiple assignment disposable
+ var SerialDisposable = Rx.SerialDisposable = function () {
+ this.isDisposed = false;
+ this.current = null;
+ };
+ SerialDisposable.prototype.getDisposable = function () {
+ return this.current;
+ };
+ SerialDisposable.prototype.setDisposable = function (value) {
+ var shouldDispose = this.isDisposed;
+ if (!shouldDispose) {
+ var old = this.current;
+ this.current = value;
+ }
+ old && old.dispose();
+ shouldDispose && value && value.dispose();
+ };
+ SerialDisposable.prototype.dispose = function () {
+ if (!this.isDisposed) {
+ this.isDisposed = true;
+ var old = this.current;
+ this.current = null;
+ }
+ 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 && !this.isInnerDisposed) {
+ this.isInnerDisposed = true;
+ this.disposable.count--;
+ if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
+ this.disposable.isDisposed = true;
+ this.disposable.underlyingDisposable.dispose();
+ }
+ }
+ };
+
+ /**
+ * Initializes a new instance of the RefCountDisposable with the specified disposable.
+ * @constructor
+ * @param {Disposable} disposable Underlying disposable.
+ */
+ function RefCountDisposable(disposable) {
+ this.underlyingDisposable = disposable;
+ this.isDisposed = false;
+ this.isPrimaryDisposed = false;
+ this.count = 0;
+ }
+
+ /**
+ * Disposes the underlying disposable only when all dependent disposables have been disposed
+ */
+ RefCountDisposable.prototype.dispose = function () {
+ if (!this.isDisposed && !this.isPrimaryDisposed) {
+ this.isPrimaryDisposed = true;
+ if (this.count === 0) {
+ this.isDisposed = true;
+ this.underlyingDisposable.dispose();
+ }
+ }
+ };
+
+ /**
+ * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
+ * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
+ */
+ RefCountDisposable.prototype.getDisposable = function () {
+ return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
+ };
+
+ return RefCountDisposable;
+ })();
+
+ function ScheduledDisposable(scheduler, disposable) {
+ this.scheduler = scheduler;
+ this.disposable = disposable;
+ this.isDisposed = false;
+ }
+
+ function scheduleItem(s, self) {
+ if (!self.isDisposed) {
+ self.isDisposed = true;
+ self.disposable.dispose();
+ }
+ }
+
+ ScheduledDisposable.prototype.dispose = function () {
+ this.scheduler.scheduleWithState(this, scheduleItem);
+ };
+
+ var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
+ this.scheduler = scheduler;
+ this.state = state;
+ this.action = action;
+ this.dueTime = dueTime;
+ this.comparer = comparer || defaultSubComparer;
+ this.disposable = new SingleAssignmentDisposable();
+ }
+
+ ScheduledItem.prototype.invoke = function () {
+ this.disposable.setDisposable(this.invokeCore());
+ };
+
+ ScheduledItem.prototype.compareTo = function (other) {
+ return this.comparer(this.dueTime, other.dueTime);
+ };
+
+ ScheduledItem.prototype.isCancelled = function () {
+ return this.disposable.isDisposed;
+ };
+
+ ScheduledItem.prototype.invokeCore = function () {
+ return this.action(this.scheduler, this.state);
+ };
+
+ /** Provides a set of static properties to access commonly used schedulers. */
+ var Scheduler = Rx.Scheduler = (function () {
+
+ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
+ this.now = now;
+ this._schedule = schedule;
+ this._scheduleRelative = scheduleRelative;
+ this._scheduleAbsolute = scheduleAbsolute;
+ }
+
+ /** Determines whether the given object is a scheduler */
+ Scheduler.isScheduler = function (s) {
+ return s instanceof Scheduler;
+ }
+
+ 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, isScheduler = Scheduler.isScheduler;
+
+ (function (schedulerProto) {
+
+ function invokeRecImmediate(scheduler, pair) {
+ var state = pair[0], action = pair[1], group = new CompositeDisposable();
+
+ function recursiveAction(state1) {
+ action(state1, function (state2) {
+ var isAdded = false, isDone = false,
+ d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
+ if (isAdded) {
+ group.remove(d);
+ } else {
+ isDone = true;
+ }
+ recursiveAction(state3);
+ return disposableEmpty;
+ });
+ if (!isDone) {
+ group.add(d);
+ isAdded = true;
+ }
+ });
+ }
+ recursiveAction(state);
+ return group;
+ }
+
+ function invokeRecDate(scheduler, pair, method) {
+ var state = pair[0], action = pair[1], group = new CompositeDisposable();
+ function recursiveAction(state1) {
+ action(state1, function (state2, dueTime1) {
+ var isAdded = false, isDone = false,
+ d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
+ if (isAdded) {
+ group.remove(d);
+ } else {
+ isDone = true;
+ }
+ recursiveAction(state3);
+ return disposableEmpty;
+ });
+ if (!isDone) {
+ group.add(d);
+ isAdded = true;
+ }
+ });
+ };
+ recursiveAction(state);
+ return group;
+ }
+
+ function scheduleInnerRecursive(action, self) {
+ action(function(dt) { self(action, dt); });
+ }
+
+ /**
+ * Schedules an action to be executed recursively.
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursive = function (action) {
+ return this.scheduleRecursiveWithState(action, scheduleInnerRecursive);
+ };
+
+ /**
+ * Schedules an action to be executed recursively.
+ * @param {Mixed} state State passed to the action to be executed.
+ * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursiveWithState = function (state, action) {
+ return this.scheduleWithState([state, action], invokeRecImmediate);
+ };
+
+ /**
+ * Schedules an action to be executed recursively after a specified relative due time.
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
+ * @param {Number}dueTime Relative time after which to execute the action for the first time.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
+ return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
+ };
+
+ /**
+ * Schedules an action to be executed recursively after a specified relative due time.
+ * @param {Mixed} state State passed to the action to be executed.
+ * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
+ * @param {Number}dueTime Relative time after which to execute the action for the first time.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
+ return this._scheduleRelative([state, action], dueTime, function (s, p) {
+ return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
+ });
+ };
+
+ /**
+ * Schedules an action to be executed recursively at a specified absolute due time.
+ * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
+ * @param {Number}dueTime Absolute time at which to execute the action for the first time.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
+ return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
+ };
+
+ /**
+ * Schedules an action to be executed recursively at a specified absolute due time.
+ * @param {Mixed} state State passed to the action to be executed.
+ * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
+ * @param {Number}dueTime Absolute time at which to execute the action for the first time.
+ * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
+ */
+ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
+ return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
+ return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
+ });
+ };
+ }(Scheduler.prototype));
+
+ (function (schedulerProto) {
+
+ /**
+ * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
+ * @param {Number} period Period for running the work periodically.
+ * @param {Function} action Action to be executed.
+ * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
+ */
+ Scheduler.prototype.schedulePeriodic = function (period, action) {
+ return this.schedulePeriodicWithState(null, period, action);
+ };
+
+ /**
+ * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
+ * @param {Mixed} state Initial state passed to the action upon the first iteration.
+ * @param {Number} period Period for running the work periodically.
+ * @param {Function} action Action to be executed, potentially updating the state.
+ * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
+ */
+ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
+ if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
+ period = normalizeTime(period);
+ var s = state, id = root.setInterval(function () { s = action(s); }, period);
+ return disposableCreate(function () { root.clearInterval(id); });
+ };
+
+ }(Scheduler.prototype));
+
+ (function (schedulerProto) {
+ /**
+ * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
+ * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
+ * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
+ */
+ schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
+ return new CatchScheduler(this, handler);
+ };
+ }(Scheduler.prototype));
+
+ var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
+ function tick(command, recurse) {
+ recurse(0, this._period);
+ try {
+ this._state = this._action(this._state);
+ } catch (e) {
+ this._cancel.dispose();
+ throw e;
+ }
+ }
+
+ function SchedulePeriodicRecursive(scheduler, state, period, action) {
+ this._scheduler = scheduler;
+ this._state = state;
+ this._period = period;
+ this._action = action;
+ }
+
+ SchedulePeriodicRecursive.prototype.start = function () {
+ var d = new SingleAssignmentDisposable();
+ this._cancel = d;
+ d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
+
+ return d;
+ };
+
+ return SchedulePeriodicRecursive;
+ }());
+
+ /** Gets a scheduler that schedules work immediately on the current thread. */
+ var immediateScheduler = Scheduler.immediate = (function () {
+ function scheduleNow(state, action) { return action(this, state); }
+ return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
+ }());
+
+ /**
+ * Gets a scheduler that schedules work as soon as possible on the current thread.
+ */
+ var currentThreadScheduler = Scheduler.currentThread = (function () {
+ var queue;
+
+ function runTrampoline () {
+ while (queue.length > 0) {
+ var item = queue.dequeue();
+ !item.isCancelled() && item.invoke();
+ }
+ }
+
+ function scheduleNow(state, action) {
+ var si = new ScheduledItem(this, state, action, this.now());
+
+ if (!queue) {
+ queue = new PriorityQueue(4);
+ queue.enqueue(si);
+
+ var result = tryCatch(runTrampoline)();
+ queue = null;
+ if (result === errorObj) { return thrower(result.e); }
+ } else {
+ queue.enqueue(si);
+ }
+ return si.disposable;
+ }
+
+ var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
+ currentScheduler.scheduleRequired = function () { return !queue; };
+
+ return currentScheduler;
+ }());
+
+ var scheduleMethod, clearMethod;
+
+ var localTimer = (function () {
+ var localSetTimeout, localClearTimeout = noop;
+ if (!!root.setTimeout) {
+ localSetTimeout = root.setTimeout;
+ localClearTimeout = root.clearTimeout;
+ } else if (!!root.WScript) {
+ localSetTimeout = function (fn, time) {
+ root.WScript.Sleep(time);
+ fn();
+ };
+ } else {
+ throw new NotSupportedError();
+ }
+
+ return {
+ setTimeout: localSetTimeout,
+ clearTimeout: localClearTimeout
+ };
+ }());
+ var localSetTimeout = localTimer.setTimeout,
+ localClearTimeout = localTimer.clearTimeout;
+
+ (function () {
+
+ var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
+
+ clearMethod = function (handle) {
+ delete tasksByHandle[handle];
+ };
+
+ function runTask(handle) {
+ if (currentlyRunning) {
+ localSetTimeout(function () { runTask(handle) }, 0);
+ } else {
+ var task = tasksByHandle[handle];
+ if (task) {
+ currentlyRunning = true;
+ var result = tryCatch(task)();
+ clearMethod(handle);
+ currentlyRunning = false;
+ if (result === errorObj) { return thrower(result.e); }
+ }
+ }
+ }
+
+ var reNative = RegExp('^' +
+ String(toString)
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ .replace(/toString| for [^\]]+/g, '.*?') + '$'
+ );
+
+ var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
+ !reNative.test(setImmediate) && setImmediate;
+
+ function postMessageSupported () {
+ // Ensure not in a worker
+ if (!root.postMessage || root.importScripts) { return false; }
+ var isAsync = false, oldHandler = root.onmessage;
+ // Test for async
+ root.onmessage = function () { isAsync = true; };
+ root.postMessage('', '*');
+ root.onmessage = oldHandler;
+
+ return isAsync;
+ }
+
+ // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
+ if (isFunction(setImmediate)) {
+ scheduleMethod = function (action) {
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+ setImmediate(function () { runTask(id); });
+
+ return id;
+ };
+ } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
+ scheduleMethod = function (action) {
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+ process.nextTick(function () { runTask(id); });
+
+ return id;
+ };
+ } else if (postMessageSupported()) {
+ var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
+
+ function onGlobalPostMessage(event) {
+ // Only if we're a match to avoid any other global events
+ if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
+ runTask(event.data.substring(MSG_PREFIX.length));
+ }
+ }
+
+ if (root.addEventListener) {
+ root.addEventListener('message', onGlobalPostMessage, false);
+ } else if (root.attachEvent) {
+ root.attachEvent('onmessage', onGlobalPostMessage);
+ } else {
+ root.onmessage = onGlobalPostMessage;
+ }
+
+ scheduleMethod = function (action) {
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+ root.postMessage(MSG_PREFIX + currentId, '*');
+ return id;
+ };
+ } else if (!!root.MessageChannel) {
+ var channel = new root.MessageChannel();
+
+ channel.port1.onmessage = function (e) { runTask(e.data); };
+
+ scheduleMethod = function (action) {
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+ channel.port2.postMessage(id);
+ return id;
+ };
+ } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
+
+ scheduleMethod = function (action) {
+ var scriptElement = root.document.createElement('script');
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+
+ scriptElement.onreadystatechange = function () {
+ runTask(id);
+ scriptElement.onreadystatechange = null;
+ scriptElement.parentNode.removeChild(scriptElement);
+ scriptElement = null;
+ };
+ root.document.documentElement.appendChild(scriptElement);
+ return id;
+ };
+
+ } else {
+ scheduleMethod = function (action) {
+ var id = nextHandle++;
+ tasksByHandle[id] = action;
+ localSetTimeout(function () {
+ runTask(id);
+ }, 0);
+
+ return id;
+ };
+ }
+ }());
+
+ /**
+ * Gets a scheduler that schedules work via a timed callback based upon platform.
+ */
+ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () {
+
+ function scheduleNow(state, action) {
+ var scheduler = this, disposable = new SingleAssignmentDisposable();
+ var id = scheduleMethod(function () {
+ !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), disposable = new SingleAssignmentDisposable();
+ if (dt === 0) { return scheduler.scheduleWithState(state, action); }
+ var id = localSetTimeout(function () {
+ !disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
+ }, dt);
+ return new CompositeDisposable(disposable, disposableCreate(function () {
+ localClearTimeout(id);
+ }));
+ }
+
+ function scheduleAbsolute(state, dueTime, action) {
+ return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
+ }
+
+ return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
+ })();
+
+ var CatchScheduler = (function (__super__) {
+
+ function scheduleNow(state, action) {
+ return this._scheduler.scheduleWithState(state, this._wrap(action));
+ }
+
+ function scheduleRelative(state, dueTime, action) {
+ return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
+ }
+
+ function scheduleAbsolute(state, dueTime, action) {
+ return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
+ }
+
+ inherits(CatchScheduler, __super__);
+
+ function CatchScheduler(scheduler, handler) {
+ this._scheduler = scheduler;
+ this._handler = handler;
+ this._recursiveOriginal = null;
+ this._recursiveWrapper = null;
+ __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
+ }
+
+ CatchScheduler.prototype._clone = function (scheduler) {
+ return new CatchScheduler(scheduler, this._handler);
+ };
+
+ CatchScheduler.prototype._wrap = function (action) {
+ var parent = this;
+ return function (self, state) {
+ try {
+ return action(parent._getRecursiveWrapper(self), state);
+ } catch (e) {
+ if (!parent._handler(e)) { throw e; }
+ return disposableEmpty;
+ }
+ };
+ };
+
+ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
+ if (this._recursiveOriginal !== scheduler) {
+ this._recursiveOriginal = scheduler;
+ var wrapper = this._clone(scheduler);
+ wrapper._recursiveOriginal = scheduler;
+ wrapper._recursiveWrapper = wrapper;
+ this._recursiveWrapper = wrapper;
+ }
+ return this._recursiveWrapper;
+ };
+
+ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
+ var self = this, failed = false, d = new SingleAssignmentDisposable();
+
+ d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
+ if (failed) { return null; }
+ try {
+ return action(state1);
+ } catch (e) {
+ failed = true;
+ if (!self._handler(e)) { throw e; }
+ d.dispose();
+ return null;
+ }
+ }));
+
+ return d;
+ };
+
+ return CatchScheduler;
+ }(Scheduler));
+
+ /**
+ * Represents a notification to an observer.
+ */
+ var Notification = Rx.Notification = (function () {
+ function Notification(kind, value, exception, accept, acceptObservable, toString) {
+ this.kind = kind;
+ this.value = value;
+ this.exception = exception;
+ this._accept = accept;
+ this._acceptObservable = acceptObservable;
+ this.toString = toString;
+ }
+
+ /**
+ * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
+ *
+ * @memberOf Notification
+ * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
+ * @param {Function} onError Delegate to invoke for an OnError notification.
+ * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
+ * @returns {Any} Result produced by the observation.
+ */
+ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
+ return observerOrOnNext && typeof observerOrOnNext === 'object' ?
+ this._acceptObservable(observerOrOnNext) :
+ this._accept(observerOrOnNext, onError, onCompleted);
+ };
+
+ /**
+ * Returns an observable sequence with a single notification.
+ *
+ * @memberOf Notifications
+ * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
+ * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
+ */
+ Notification.prototype.toObservable = function (scheduler) {
+ var self = this;
+ isScheduler(scheduler) || (scheduler = immediateScheduler);
+ return new AnonymousObservable(function (observer) {
+ return scheduler.scheduleWithState(self, function (_, notification) {
+ notification._acceptObservable(observer);
+ notification.kind === 'N' && observer.onCompleted();
+ });
+ });
+ };
+
+ return Notification;
+ })();
+
+ /**
+ * Creates an object that represents an OnNext notification to an observer.
+ * @param {Any} value The value contained in the notification.
+ * @returns {Notification} The OnNext notification containing the value.
+ */
+ var notificationCreateOnNext = Notification.createOnNext = (function () {
+ function _accept(onNext) { return onNext(this.value); }
+ function _acceptObservable(observer) { return observer.onNext(this.value); }
+ function toString() { return 'OnNext(' + this.value + ')'; }
+
+ return function (value) {
+ return new Notification('N', value, null, _accept, _acceptObservable, toString);
+ };
+ }());
+
+ /**
+ * Creates an object that represents an OnError notification to an observer.
+ * @param {Any} error The exception contained in the notification.
+ * @returns {Notification} The OnError notification containing the exception.
+ */
+ var notificationCreateOnError = Notification.createOnError = (function () {
+ function _accept (onNext, onError) { return onError(this.exception); }
+ function _acceptObservable(observer) { return observer.onError(this.exception); }
+ function toString () { return 'OnError(' + this.exception + ')'; }
+
+ return function (e) {
+ return new Notification('E', null, e, _accept, _acceptObservable, toString);
+ };
+ }());
+
+ /**
+ * Creates an object that represents an OnCompleted notification to an observer.
+ * @returns {Notification} The OnCompleted notification.
+ */
+ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
+ function _accept (onNext, onError, onCompleted) { return onCompleted(); }
+ function _acceptObservable(observer) { return observer.onCompleted(); }
+ function toString () { return 'OnCompleted()'; }
+
+ return function () {
+ return new Notification('C', null, null, _accept, _acceptObservable, toString);
+ };
+ }());
+
+ /**
+ * Supports push-style iteration over an observable sequence.
+ */
+ var Observer = Rx.Observer = function () { };
+
+ /**
+ * Creates a notification callback from an observer.
+ * @returns The action that forwards its input notification to the underlying observer.
+ */
+ Observer.prototype.toNotifier = function () {
+ var observer = this;
+ return function (n) { return n.accept(observer); };
+ };
+
+ /**
+ * Hides the identity of an observer.
+ * @returns An observer that hides the identity of the specified observer.
+ */
+ Observer.prototype.asObserver = function () {
+ return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
+ };
+
+ /**
+ * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
+ * If a violation is detected, an Error is thrown from the offending observer method call.
+ * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
+ */
+ Observer.prototype.checked = function () { return new CheckedObserver(this); };
+
+ /**
+ * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
+ * @param {Function} [onNext] Observer's OnNext action implementation.
+ * @param {Function} [onError] Observer's OnError action implementation.
+ * @param {Function} [onCompleted] Observer's OnCompleted action implementation.
+ * @returns {Observer} The observer object implemented using the given actions.
+ */
+ var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
+ onNext || (onNext = noop);
+ onError || (onError = defaultError);
+ onCompleted || (onCompleted = noop);
+ return new AnonymousObserver(onNext, onError, onCompleted);
+ };
+
+ /**
+ * Creates an observer from a notification callback.
+ *
+ * @static
+ * @memberOf Observer
+ * @param {Function} handler Action that handles a notification.
+ * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
+ */
+ Observer.fromNotifier = function (handler, thisArg) {
+ return new AnonymousObserver(function (x) {
+ return handler.call(thisArg, notificationCreateOnNext(x));
+ }, function (e) {
+ return handler.call(thisArg, notificationCreateOnError(e));
+ }, function () {
+ return handler.call(thisArg, notificationCreateOnCompleted());
+ });
+ };
+
+ /**
+ * Schedules the invocation of observer methods on the given scheduler.
+ * @param {Scheduler} scheduler Scheduler to schedule observer messages on.
+ * @returns {Observer} Observer whose messages are scheduled on the given scheduler.
+ */
+ Observer.prototype.notifyOn = function (scheduler) {
+ return new ObserveOnObserver(scheduler, this);
+ };
+
+ Observer.prototype.makeSafe = function(disposable) {
+ return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
+ };
+
+ /**
+ * Abstract base class for implementations of the Observer class.
+ * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
+ */
+ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
+ inherits(AbstractObserver, __super__);
+
+ /**
+ * Creates a new observer in a non-stopped state.
+ */
+ function AbstractObserver() {
+ this.isStopped = false;
+ __super__.call(this);
+ }
+
+ // Must be implemented by other observers
+ AbstractObserver.prototype.next = notImplemented;
+ AbstractObserver.prototype.error = notImplemented;
+ AbstractObserver.prototype.completed = notImplemented;
+
+ /**
+ * Notifies the observer of a new element in the sequence.
+ * @param {Any} value Next element in the sequence.
+ */
+ AbstractObserver.prototype.onNext = function (value) {
+ if (!this.isStopped) { this.next(value); }
+ };
+
+ /**
+ * Notifies the observer that an exception has occurred.
+ * @param {Any} error The error that has occurred.
+ */
+ AbstractObserver.prototype.onError = function (error) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.error(error);
+ }
+ };
+
+ /**
+ * Notifies the observer of the end of the sequence.
+ */
+ AbstractObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.completed();
+ }
+ };
+
+ /**
+ * Disposes the observer, causing it to transition to the stopped state.
+ */
+ AbstractObserver.prototype.dispose = function () {
+ this.isStopped = true;
+ };
+
+ AbstractObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.error(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return AbstractObserver;
+ }(Observer));
+
+ /**
+ * Class to create an Observer instance from delegate-based implementations of the on* methods.
+ */
+ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
+ inherits(AnonymousObserver, __super__);
+
+ /**
+ * Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
+ * @param {Any} onNext Observer's OnNext action implementation.
+ * @param {Any} onError Observer's OnError action implementation.
+ * @param {Any} onCompleted Observer's OnCompleted action implementation.
+ */
+ function AnonymousObserver(onNext, onError, onCompleted) {
+ __super__.call(this);
+ this._onNext = onNext;
+ this._onError = onError;
+ this._onCompleted = onCompleted;
+ }
+
+ /**
+ * Calls the onNext action.
+ * @param {Any} value Next element in the sequence.
+ */
+ AnonymousObserver.prototype.next = function (value) {
+ this._onNext(value);
+ };
+
+ /**
+ * Calls the onError action.
+ * @param {Any} error The error that has occurred.
+ */
+ AnonymousObserver.prototype.error = function (error) {
+ this._onError(error);
+ };
+
+ /**
+ * Calls the onCompleted action.
+ */
+ AnonymousObserver.prototype.completed = function () {
+ this._onCompleted();
+ };
+
+ return AnonymousObserver;
+ }(AbstractObserver));
+
+ var CheckedObserver = (function (__super__) {
+ inherits(CheckedObserver, __super__);
+
+ function CheckedObserver(observer) {
+ __super__.call(this);
+ this._observer = observer;
+ this._state = 0; // 0 - idle, 1 - busy, 2 - done
+ }
+
+ var CheckedObserverPrototype = CheckedObserver.prototype;
+
+ CheckedObserverPrototype.onNext = function (value) {
+ this.checkAccess();
+ var res = tryCatch(this._observer.onNext).call(this._observer, value);
+ this._state = 0;
+ res === errorObj && thrower(res.e);
+ };
+
+ CheckedObserverPrototype.onError = function (err) {
+ this.checkAccess();
+ var res = tryCatch(this._observer.onError).call(this._observer, err);
+ this._state = 2;
+ res === errorObj && thrower(res.e);
+ };
+
+ CheckedObserverPrototype.onCompleted = function () {
+ this.checkAccess();
+ var res = tryCatch(this._observer.onCompleted).call(this._observer);
+ this._state = 2;
+ res === errorObj && thrower(res.e);
+ };
+
+ CheckedObserverPrototype.checkAccess = function () {
+ if (this._state === 1) { throw new Error('Re-entrancy detected'); }
+ if (this._state === 2) { throw new Error('Observer completed'); }
+ if (this._state === 0) { this._state = 1; }
+ };
+
+ return CheckedObserver;
+ }(Observer));
+
+ var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
+ inherits(ScheduledObserver, __super__);
+
+ function ScheduledObserver(scheduler, observer) {
+ __super__.call(this);
+ this.scheduler = scheduler;
+ this.observer = observer;
+ this.isAcquired = false;
+ this.hasFaulted = false;
+ this.queue = [];
+ this.disposable = new SerialDisposable();
+ }
+
+ ScheduledObserver.prototype.next = function (value) {
+ var self = this;
+ this.queue.push(function () { self.observer.onNext(value); });
+ };
+
+ ScheduledObserver.prototype.error = function (e) {
+ var self = this;
+ this.queue.push(function () { self.observer.onError(e); });
+ };
+
+ ScheduledObserver.prototype.completed = function () {
+ var self = this;
+ this.queue.push(function () { self.observer.onCompleted(); });
+ };
+
+ ScheduledObserver.prototype.ensureActive = function () {
+ var isOwner = false, parent = this;
+ if (!this.hasFaulted && this.queue.length > 0) {
+ isOwner = !this.isAcquired;
+ this.isAcquired = true;
+ }
+ if (isOwner) {
+ this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
+ var work;
+ if (parent.queue.length > 0) {
+ work = parent.queue.shift();
+ } else {
+ parent.isAcquired = false;
+ return;
+ }
+ try {
+ work();
+ } catch (ex) {
+ parent.queue = [];
+ parent.hasFaulted = true;
+ throw ex;
+ }
+ self();
+ }));
+ }
+ };
+
+ ScheduledObserver.prototype.dispose = function () {
+ __super__.prototype.dispose.call(this);
+ this.disposable.dispose();
+ };
+
+ return ScheduledObserver;
+ }(AbstractObserver));
+
+ var ObserveOnObserver = (function (__super__) {
+ inherits(ObserveOnObserver, __super__);
+
+ function ObserveOnObserver(scheduler, observer, cancel) {
+ __super__.call(this, scheduler, observer);
+ this._cancel = cancel;
+ }
+
+ ObserveOnObserver.prototype.next = function (value) {
+ __super__.prototype.next.call(this, value);
+ this.ensureActive();
+ };
+
+ ObserveOnObserver.prototype.error = function (e) {
+ __super__.prototype.error.call(this, e);
+ this.ensureActive();
+ };
+
+ ObserveOnObserver.prototype.completed = function () {
+ __super__.prototype.completed.call(this);
+ this.ensureActive();
+ };
+
+ ObserveOnObserver.prototype.dispose = function () {
+ __super__.prototype.dispose.call(this);
+ this._cancel && this._cancel.dispose();
+ this._cancel = null;
+ };
+
+ return ObserveOnObserver;
+ })(ScheduledObserver);
+
+ var observableProto;
+
+ /**
+ * Represents a push-style collection.
+ */
+ var Observable = Rx.Observable = (function () {
+
+ function Observable(subscribe) {
+ if (Rx.config.longStackSupport && hasStacks) {
+ try {
+ throw new Error();
+ } catch (e) {
+ this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
+ }
+
+ var self = this;
+ this._subscribe = function (observer) {
+ var oldOnError = observer.onError.bind(observer);
+
+ observer.onError = function (err) {
+ makeStackTraceLong(err, self);
+ oldOnError(err);
+ };
+
+ return subscribe.call(self, observer);
+ };
+ } else {
+ this._subscribe = subscribe;
+ }
+ }
+
+ observableProto = Observable.prototype;
+
+ /**
+ * Subscribes an observer to the observable sequence.
+ * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
+ * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
+ * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
+ * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
+ */
+ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
+ return this._subscribe(typeof observerOrOnNext === 'object' ?
+ observerOrOnNext :
+ observerCreate(observerOrOnNext, onError, onCompleted));
+ };
+
+ /**
+ * Subscribes to the next value in the sequence with an optional "this" argument.
+ * @param {Function} onNext The function to invoke on each element in the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
+ */
+ observableProto.subscribeOnNext = function (onNext, thisArg) {
+ return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
+ };
+
+ /**
+ * Subscribes to an exceptional condition in the sequence with an optional "this" argument.
+ * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
+ */
+ observableProto.subscribeOnError = function (onError, thisArg) {
+ return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
+ };
+
+ /**
+ * Subscribes to the next value in the sequence with an optional "this" argument.
+ * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
+ */
+ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
+ return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
+ };
+
+ return Observable;
+ })();
+
+ var ObservableBase = Rx.ObservableBase = (function (__super__) {
+ inherits(ObservableBase, __super__);
+
+ function fixSubscriber(subscriber) {
+ return subscriber && isFunction(subscriber.dispose) ? subscriber :
+ isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
+ }
+
+ function setDisposable(s, state) {
+ var ado = state[0], self = state[1];
+ var sub = tryCatch(self.subscribeCore).call(self, ado);
+
+ if (sub === errorObj) {
+ if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
+ }
+ ado.setDisposable(fixSubscriber(sub));
+ }
+
+ function subscribe(observer) {
+ var ado = new AutoDetachObserver(observer), state = [ado, this];
+
+ if (currentThreadScheduler.scheduleRequired()) {
+ currentThreadScheduler.scheduleWithState(state, setDisposable);
+ } else {
+ setDisposable(null, state);
+ }
+ return ado;
+ }
+
+ function ObservableBase() {
+ __super__.call(this, subscribe);
+ }
+
+ ObservableBase.prototype.subscribeCore = notImplemented;
+
+ return ObservableBase;
+ }(Observable));
+
+ var Enumerable = Rx.internals.Enumerable = function () { };
+
+ var ConcatEnumerableObservable = (function(__super__) {
+ inherits(ConcatEnumerableObservable, __super__);
+ function ConcatEnumerableObservable(sources) {
+ this.sources = sources;
+ __super__.call(this);
+ }
+
+ ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
+ var isDisposed, subscription = new SerialDisposable();
+ var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) {
+ if (isDisposed) { return; }
+ var currentItem = tryCatch(e.next).call(e);
+ if (currentItem === errorObj) { return o.onError(currentItem.e); }
+
+ if (currentItem.done) {
+ return o.onCompleted();
+ }
+
+ // Check if promise
+ var currentValue = currentItem.value;
+ isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
+
+ var d = new SingleAssignmentDisposable();
+ subscription.setDisposable(d);
+ d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e)));
+ });
+
+ return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
+ isDisposed = true;
+ }));
+ };
+
+ function InnerObserver(o, s, e) {
+ this.o = o;
+ this.s = s;
+ this.e = e;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } };
+ InnerObserver.prototype.onError = function (err) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(err);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.s(this.e);
+ }
+ };
+ InnerObserver.prototype.dispose = function () { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (err) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(err);
+ return true;
+ }
+ return false;
+ };
+
+ return ConcatEnumerableObservable;
+ }(ObservableBase));
+
+ Enumerable.prototype.concat = function () {
+ return new ConcatEnumerableObservable(this);
+ };
+
+ var CatchErrorObservable = (function(__super__) {
+ inherits(CatchErrorObservable, __super__);
+ function CatchErrorObservable(sources) {
+ this.sources = sources;
+ __super__.call(this);
+ }
+
+ CatchErrorObservable.prototype.subscribeCore = function (o) {
+ var e = this.sources[$iterator$]();
+
+ var isDisposed, subscription = new SerialDisposable();
+ var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
+ if (isDisposed) { return; }
+ var currentItem = tryCatch(e.next).call(e);
+ if (currentItem === errorObj) { return o.onError(currentItem.e); }
+
+ if (currentItem.done) {
+ return lastException !== null ? o.onError(lastException) : o.onCompleted();
+ }
+
+ // Check if promise
+ var currentValue = currentItem.value;
+ isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
+
+ var d = new SingleAssignmentDisposable();
+ subscription.setDisposable(d);
+ d.setDisposable(currentValue.subscribe(
+ function(x) { o.onNext(x); },
+ self,
+ function() { o.onCompleted(); }));
+ });
+ return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
+ isDisposed = true;
+ }));
+ };
+
+ return CatchErrorObservable;
+ }(ObservableBase));
+
+ Enumerable.prototype.catchError = function () {
+ return new CatchErrorObservable(this);
+ };
+
+ Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
+ var sources = this;
+ return new AnonymousObservable(function (o) {
+ var exceptions = new Subject(),
+ notifier = new Subject(),
+ handled = notificationHandler(exceptions),
+ notificationDisposable = handled.subscribe(notifier);
+
+ var e = sources[$iterator$]();
+
+ var isDisposed,
+ lastException,
+ subscription = new SerialDisposable();
+ var cancelable = immediateScheduler.scheduleRecursive(function (self) {
+ if (isDisposed) { return; }
+ var currentItem = tryCatch(e.next).call(e);
+ if (currentItem === errorObj) { return o.onError(currentItem.e); }
+
+ if (currentItem.done) {
+ if (lastException) {
+ o.onError(lastException);
+ } else {
+ o.onCompleted();
+ }
+ return;
+ }
+
+ // Check if promise
+ var currentValue = currentItem.value;
+ isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
+
+ var outer = new SingleAssignmentDisposable();
+ var inner = new SingleAssignmentDisposable();
+ subscription.setDisposable(new CompositeDisposable(inner, outer));
+ outer.setDisposable(currentValue.subscribe(
+ function(x) { o.onNext(x); },
+ function (exn) {
+ inner.setDisposable(notifier.subscribe(self, function(ex) {
+ o.onError(ex);
+ }, function() {
+ o.onCompleted();
+ }));
+
+ exceptions.onNext(exn);
+ },
+ function() { o.onCompleted(); }));
+ });
+
+ return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
+ isDisposed = true;
+ }));
+ });
+ };
+
+ var RepeatEnumerable = (function (__super__) {
+ inherits(RepeatEnumerable, __super__);
+
+ function RepeatEnumerable(v, c) {
+ this.v = v;
+ this.c = c == null ? -1 : c;
+ }
+ RepeatEnumerable.prototype[$iterator$] = function () {
+ return new RepeatEnumerator(this);
+ };
+
+ function RepeatEnumerator(p) {
+ this.v = p.v;
+ this.l = p.c;
+ }
+ RepeatEnumerator.prototype.next = function () {
+ if (this.l === 0) { return doneEnumerator; }
+ if (this.l > 0) { this.l--; }
+ return { done: false, value: this.v };
+ };
+
+ return RepeatEnumerable;
+ }(Enumerable));
+
+ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
+ return new RepeatEnumerable(value, repeatCount);
+ };
+
+ var OfEnumerable = (function(__super__) {
+ inherits(OfEnumerable, __super__);
+ function OfEnumerable(s, fn, thisArg) {
+ this.s = s;
+ this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
+ }
+ OfEnumerable.prototype[$iterator$] = function () {
+ return new OfEnumerator(this);
+ };
+
+ function OfEnumerator(p) {
+ this.i = -1;
+ this.s = p.s;
+ this.l = this.s.length;
+ this.fn = p.fn;
+ }
+ OfEnumerator.prototype.next = function () {
+ return ++this.i < this.l ?
+ { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
+ doneEnumerator;
+ };
+
+ return OfEnumerable;
+ }(Enumerable));
+
+ var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
+ return new OfEnumerable(source, selector, thisArg);
+ };
+
+ /**
+ * Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
+ *
+ * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
+ * that require to be run on a scheduler, use subscribeOn.
+ *
+ * @param {Scheduler} scheduler Scheduler to notify observers on.
+ * @returns {Observable} The source sequence whose observations happen on the specified scheduler.
+ */
+ observableProto.observeOn = function (scheduler) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ return source.subscribe(new ObserveOnObserver(scheduler, observer));
+ }, source);
+ };
+
+ /**
+ * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
+ * see the remarks section for more information on the distinction between subscribeOn and observeOn.
+
+ * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
+ * callbacks on a scheduler, use observeOn.
+
+ * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
+ * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
+ */
+ observableProto.subscribeOn = function (scheduler) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
+ d.setDisposable(m);
+ m.setDisposable(scheduler.schedule(function () {
+ d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
+ }));
+ return d;
+ }, source);
+ };
+
+ var FromPromiseObservable = (function(__super__) {
+ inherits(FromPromiseObservable, __super__);
+ function FromPromiseObservable(p) {
+ this.p = p;
+ __super__.call(this);
+ }
+
+ FromPromiseObservable.prototype.subscribeCore = function(o) {
+ this.p.then(function (data) {
+ o.onNext(data);
+ o.onCompleted();
+ }, function (err) { o.onError(err); });
+ return disposableEmpty;
+ };
+
+ return FromPromiseObservable;
+ }(ObservableBase));
+
+ /**
+ * 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 FromPromiseObservable(promise);
+ };
+ /*
+ * Converts an existing observable sequence to an ES6 Compatible Promise
+ * @example
+ * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
+ *
+ * // With config
+ * Rx.config.Promise = RSVP.Promise;
+ * var promise = Rx.Observable.return(42).toPromise();
+ * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
+ * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
+ */
+ observableProto.toPromise = function (promiseCtor) {
+ promiseCtor || (promiseCtor = Rx.config.Promise);
+ if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
+ var source = this;
+ return new promiseCtor(function (resolve, reject) {
+ // No cancellation can be done
+ var value, hasValue = false;
+ source.subscribe(function (v) {
+ value = v;
+ hasValue = true;
+ }, reject, function () {
+ hasValue && resolve(value);
+ });
+ });
+ };
+
+ var ToArrayObservable = (function(__super__) {
+ inherits(ToArrayObservable, __super__);
+ function ToArrayObservable(source) {
+ this.source = source;
+ __super__.call(this);
+ }
+
+ ToArrayObservable.prototype.subscribeCore = function(o) {
+ return this.source.subscribe(new InnerObserver(o));
+ };
+
+ function InnerObserver(o) {
+ this.o = o;
+ this.a = [];
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
+ InnerObserver.prototype.onError = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onNext(this.a);
+ this.o.onCompleted();
+ }
+ };
+ InnerObserver.prototype.dispose = function () { this.isStopped = true; }
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return ToArrayObservable;
+ }(ObservableBase));
+
+ /**
+ * Creates an array from an observable sequence.
+ * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
+ */
+ observableProto.toArray = function () {
+ return new ToArrayObservable(this);
+ };
+
+ /**
+ * Creates an observable sequence from a specified subscribe method implementation.
+ * @example
+ * var res = Rx.Observable.create(function (observer) { return function () { } );
+ * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
+ * var res = Rx.Observable.create(function (observer) { } );
+ * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
+ * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
+ */
+ Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
+ return new AnonymousObservable(subscribe, parent);
+ };
+
+ /**
+ * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
+ *
+ * @example
+ * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
+ * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
+ * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
+ */
+ var observableDefer = Observable.defer = function (observableFactory) {
+ return new AnonymousObservable(function (observer) {
+ var result;
+ try {
+ result = observableFactory();
+ } catch (e) {
+ return observableThrow(e).subscribe(observer);
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ return result.subscribe(observer);
+ });
+ };
+
+ var EmptyObservable = (function(__super__) {
+ inherits(EmptyObservable, __super__);
+ function EmptyObservable(scheduler) {
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ EmptyObservable.prototype.subscribeCore = function (observer) {
+ var sink = new EmptySink(observer, this);
+ return sink.run();
+ };
+
+ function EmptySink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ function scheduleItem(s, state) {
+ state.onCompleted();
+ }
+
+ EmptySink.prototype.run = function () {
+ return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem);
+ };
+
+ return EmptyObservable;
+ }(ObservableBase));
+
+ /**
+ * 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 EmptyObservable(scheduler);
+ };
+
+ var FromObservable = (function(__super__) {
+ inherits(FromObservable, __super__);
+ function FromObservable(iterable, mapper, scheduler) {
+ this.iterable = iterable;
+ this.mapper = mapper;
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ FromObservable.prototype.subscribeCore = function (observer) {
+ var sink = new FromSink(observer, this);
+ return sink.run();
+ };
+
+ return FromObservable;
+ }(ObservableBase));
+
+ var FromSink = (function () {
+ function FromSink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ FromSink.prototype.run = function () {
+ var list = Object(this.parent.iterable),
+ it = getIterable(list),
+ observer = this.observer,
+ mapper = this.parent.mapper;
+
+ function loopRecursive(i, recurse) {
+ try {
+ var next = it.next();
+ } catch (e) {
+ return observer.onError(e);
+ }
+ if (next.done) {
+ return observer.onCompleted();
+ }
+
+ var result = next.value;
+
+ if (mapper) {
+ try {
+ result = mapper(result, i);
+ } catch (e) {
+ return observer.onError(e);
+ }
+ }
+
+ observer.onNext(result);
+ recurse(i + 1);
+ }
+
+ return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
+ };
+
+ return FromSink;
+ }());
+
+ var maxSafeInteger = Math.pow(2, 53) - 1;
+
+ function StringIterable(str) {
+ this._s = s;
+ }
+
+ StringIterable.prototype[$iterator$] = function () {
+ return new StringIterator(this._s);
+ };
+
+ function StringIterator(str) {
+ this._s = s;
+ this._l = s.length;
+ this._i = 0;
+ }
+
+ StringIterator.prototype[$iterator$] = function () {
+ return this;
+ };
+
+ StringIterator.prototype.next = function () {
+ return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
+ };
+
+ function ArrayIterable(a) {
+ this._a = a;
+ }
+
+ ArrayIterable.prototype[$iterator$] = function () {
+ return new ArrayIterator(this._a);
+ };
+
+ function ArrayIterator(a) {
+ this._a = a;
+ this._l = toLength(a);
+ this._i = 0;
+ }
+
+ ArrayIterator.prototype[$iterator$] = function () {
+ return this;
+ };
+
+ ArrayIterator.prototype.next = function () {
+ return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
+ };
+
+ function numberIsFinite(value) {
+ return typeof value === 'number' && root.isFinite(value);
+ }
+
+ function isNan(n) {
+ return n !== n;
+ }
+
+ function getIterable(o) {
+ var i = o[$iterator$], it;
+ if (!i && typeof o === 'string') {
+ it = new StringIterable(o);
+ return it[$iterator$]();
+ }
+ if (!i && o.length !== undefined) {
+ it = new ArrayIterable(o);
+ return it[$iterator$]();
+ }
+ if (!i) { throw new TypeError('Object is not iterable'); }
+ return o[$iterator$]();
+ }
+
+ function sign(value) {
+ var number = +value;
+ if (number === 0) { return number; }
+ if (isNaN(number)) { return number; }
+ return number < 0 ? -1 : 1;
+ }
+
+ function toLength(o) {
+ var len = +o.length;
+ if (isNaN(len)) { return 0; }
+ if (len === 0 || !numberIsFinite(len)) { return len; }
+ len = sign(len) * Math.floor(Math.abs(len));
+ if (len <= 0) { return 0; }
+ if (len > maxSafeInteger) { return maxSafeInteger; }
+ return len;
+ }
+
+ /**
+ * This method creates a new Observable sequence from an array-like or iterable object.
+ * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
+ * @param {Function} [mapFn] Map function to call on every element of the array.
+ * @param {Any} [thisArg] The context to use calling the mapFn if provided.
+ * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
+ */
+ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
+ if (iterable == null) {
+ throw new Error('iterable cannot be null.')
+ }
+ if (mapFn && !isFunction(mapFn)) {
+ throw new Error('mapFn when provided must be a function');
+ }
+ if (mapFn) {
+ var mapper = bindCallback(mapFn, thisArg, 2);
+ }
+ isScheduler(scheduler) || (scheduler = currentThreadScheduler);
+ return new FromObservable(iterable, mapper, scheduler);
+ }
+
+ var FromArrayObservable = (function(__super__) {
+ inherits(FromArrayObservable, __super__);
+ function FromArrayObservable(args, scheduler) {
+ this.args = args;
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ FromArrayObservable.prototype.subscribeCore = function (observer) {
+ var sink = new FromArraySink(observer, this);
+ return sink.run();
+ };
+
+ return FromArrayObservable;
+ }(ObservableBase));
+
+ function FromArraySink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ FromArraySink.prototype.run = function () {
+ var observer = this.observer, args = this.parent.args, len = args.length;
+ function loopRecursive(i, recurse) {
+ if (i < len) {
+ observer.onNext(args[i]);
+ recurse(i + 1);
+ } else {
+ observer.onCompleted();
+ }
+ }
+
+ return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
+ };
+
+ /**
+ * Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
+ * @deprecated use Observable.from or Observable.of
+ * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
+ * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
+ */
+ var observableFromArray = Observable.fromArray = function (array, scheduler) {
+ isScheduler(scheduler) || (scheduler = currentThreadScheduler);
+ return new FromArrayObservable(array, scheduler)
+ };
+
+ /**
+ * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
+ *
+ * @example
+ * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
+ * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
+ * @param {Mixed} initialState Initial state.
+ * @param {Function} condition Condition to terminate generation (upon returning false).
+ * @param {Function} iterate Iteration step function.
+ * @param {Function} resultSelector Selector function for results produced in the sequence.
+ * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
+ * @returns {Observable} The generated sequence.
+ */
+ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
+ isScheduler(scheduler) || (scheduler = currentThreadScheduler);
+ return new AnonymousObservable(function (o) {
+ var first = true;
+ return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
+ var hasResult, result;
+ try {
+ if (first) {
+ first = false;
+ } else {
+ state = iterate(state);
+ }
+ hasResult = condition(state);
+ hasResult && (result = resultSelector(state));
+ } catch (e) {
+ return o.onError(e);
+ }
+ if (hasResult) {
+ o.onNext(result);
+ self(state);
+ } else {
+ o.onCompleted();
+ }
+ });
+ });
+ };
+
+ var NeverObservable = (function(__super__) {
+ inherits(NeverObservable, __super__);
+ function NeverObservable() {
+ __super__.call(this);
+ }
+
+ NeverObservable.prototype.subscribeCore = function (observer) {
+ return disposableEmpty;
+ };
+
+ return NeverObservable;
+ }(ObservableBase));
+
+ /**
+ * 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 NeverObservable();
+ };
+
+ function observableOf (scheduler, array) {
+ isScheduler(scheduler) || (scheduler = currentThreadScheduler);
+ return new FromArrayObservable(array, scheduler);
+ }
+
+ /**
+ * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
+ * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
+ */
+ Observable.of = function () {
+ var len = arguments.length, args = new Array(len);
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ return new FromArrayObservable(args, currentThreadScheduler);
+ };
+
+ /**
+ * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
+ * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
+ * @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
+ */
+ Observable.ofWithScheduler = function (scheduler) {
+ var len = arguments.length, args = new Array(len - 1);
+ for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
+ return new FromArrayObservable(args, scheduler);
+ };
+
+ var PairsObservable = (function(__super__) {
+ inherits(PairsObservable, __super__);
+ function PairsObservable(obj, scheduler) {
+ this.obj = obj;
+ this.keys = Object.keys(obj);
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ PairsObservable.prototype.subscribeCore = function (observer) {
+ var sink = new PairsSink(observer, this);
+ return sink.run();
+ };
+
+ return PairsObservable;
+ }(ObservableBase));
+
+ function PairsSink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ PairsSink.prototype.run = function () {
+ var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length;
+ function loopRecursive(i, recurse) {
+ if (i < len) {
+ var key = keys[i];
+ observer.onNext([key, obj[key]]);
+ recurse(i + 1);
+ } else {
+ observer.onCompleted();
+ }
+ }
+
+ return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
+ };
+
+ /**
+ * Convert an object into an observable sequence of [key, value] pairs.
+ * @param {Object} obj The object to inspect.
+ * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
+ * @returns {Observable} An observable sequence of [key, value] pairs from the object.
+ */
+ Observable.pairs = function (obj, scheduler) {
+ scheduler || (scheduler = currentThreadScheduler);
+ return new PairsObservable(obj, scheduler);
+ };
+
+ var RangeObservable = (function(__super__) {
+ inherits(RangeObservable, __super__);
+ function RangeObservable(start, count, scheduler) {
+ this.start = start;
+ this.rangeCount = count;
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ RangeObservable.prototype.subscribeCore = function (observer) {
+ var sink = new RangeSink(observer, this);
+ return sink.run();
+ };
+
+ return RangeObservable;
+ }(ObservableBase));
+
+ var RangeSink = (function () {
+ function RangeSink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ RangeSink.prototype.run = function () {
+ var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer;
+ function loopRecursive(i, recurse) {
+ if (i < count) {
+ observer.onNext(start + i);
+ recurse(i + 1);
+ } else {
+ observer.onCompleted();
+ }
+ }
+
+ return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
+ };
+
+ return RangeSink;
+ }());
+
+ /**
+ * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
+ * @param {Number} start The value of the first integer in the sequence.
+ * @param {Number} count The number of sequential integers to generate.
+ * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
+ * @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
+ */
+ Observable.range = function (start, count, scheduler) {
+ isScheduler(scheduler) || (scheduler = currentThreadScheduler);
+ return new RangeObservable(start, count, scheduler);
+ };
+
+ var RepeatObservable = (function(__super__) {
+ inherits(RepeatObservable, __super__);
+ function RepeatObservable(value, repeatCount, scheduler) {
+ this.value = value;
+ this.repeatCount = repeatCount == null ? -1 : repeatCount;
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ RepeatObservable.prototype.subscribeCore = function (observer) {
+ var sink = new RepeatSink(observer, this);
+ return sink.run();
+ };
+
+ return RepeatObservable;
+ }(ObservableBase));
+
+ function RepeatSink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ RepeatSink.prototype.run = function () {
+ var observer = this.observer, value = this.parent.value;
+ function loopRecursive(i, recurse) {
+ if (i === -1 || i > 0) {
+ observer.onNext(value);
+ i > 0 && i--;
+ }
+ if (i === 0) { return observer.onCompleted(); }
+ recurse(i);
+ }
+
+ return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive);
+ };
+
+ /**
+ * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
+ * @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 new RepeatObservable(value, repeatCount, scheduler);
+ };
+
+ var JustObservable = (function(__super__) {
+ inherits(JustObservable, __super__);
+ function JustObservable(value, scheduler) {
+ this.value = value;
+ this.scheduler = scheduler;
+ __super__.call(this);
+ }
+
+ JustObservable.prototype.subscribeCore = function (observer) {
+ var sink = new JustSink(observer, this);
+ return sink.run();
+ };
+
+ function JustSink(observer, parent) {
+ this.observer = observer;
+ this.parent = parent;
+ }
+
+ function scheduleItem(s, state) {
+ var value = state[0], observer = state[1];
+ observer.onNext(value);
+ observer.onCompleted();
+ }
+
+ JustSink.prototype.run = function () {
+ return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem);
+ };
+
+ return JustObservable;
+ }(ObservableBase));
+
+ /**
+ * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
+ * There is an alias called 'just' or browsers 0) {
+ parent.handleSubscribe(parent.q.shift());
+ } else {
+ parent.activeCount--;
+ parent.done && parent.activeCount === 0 && parent.o.onCompleted();
+ }
+ }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.parent.o.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return MergeObserver;
+ }());
+
+
+
+
+
+ /**
+ * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
+ * Or merges two observable sequences into a single observable sequence.
+ *
+ * @example
+ * 1 - merged = sources.merge(1);
+ * 2 - merged = source.merge(otherSource);
+ * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
+ * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
+ */
+ observableProto.merge = function (maxConcurrentOrOther) {
+ return typeof maxConcurrentOrOther !== 'number' ?
+ observableMerge(this, maxConcurrentOrOther) :
+ new MergeObservable(this, maxConcurrentOrOther);
+ };
+
+ /**
+ * Merges all the observable sequences into a single observable sequence.
+ * The scheduler is optional and if not specified, the immediate scheduler is used.
+ * @returns {Observable} The observable sequence that merges the elements of the observable sequences.
+ */
+ var observableMerge = Observable.merge = function () {
+ var scheduler, sources = [], i, len = arguments.length;
+ if (!arguments[0]) {
+ scheduler = immediateScheduler;
+ for(i = 1; i < len; i++) { sources.push(arguments[i]); }
+ } else if (isScheduler(arguments[0])) {
+ scheduler = arguments[0];
+ for(i = 1; i < len; i++) { sources.push(arguments[i]); }
+ } else {
+ scheduler = immediateScheduler;
+ for(i = 0; i < len; i++) { sources.push(arguments[i]); }
+ }
+ if (Array.isArray(sources[0])) {
+ sources = sources[0];
+ }
+ return observableOf(scheduler, sources).mergeAll();
+ };
+
+ var CompositeError = Rx.CompositeError = function(errors) {
+ this.name = "NotImplementedError";
+ this.innerErrors = errors;
+ this.message = 'This contains multiple errors. Check the innerErrors';
+ Error.call(this);
+ }
+ CompositeError.prototype = Error.prototype;
+
+ /**
+ * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
+ * receive all successfully emitted items from all of the source Observables without being interrupted by
+ * an error notification from one of them.
+ *
+ * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
+ * error via the Observer's onError, mergeDelayError will refrain from propagating that
+ * error notification until all of the merged Observables have finished emitting items.
+ * @param {Array | Arguments} args Arguments or an array to merge.
+ * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
+ */
+ Observable.mergeDelayError = function() {
+ var args;
+ if (Array.isArray(arguments[0])) {
+ args = arguments[0];
+ } else {
+ var len = arguments.length;
+ args = new Array(len);
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ }
+ var source = observableOf(null, args);
+
+ return new AnonymousObservable(function (o) {
+ var group = new CompositeDisposable(),
+ m = new SingleAssignmentDisposable(),
+ isStopped = false,
+ errors = [];
+
+ function setCompletion() {
+ if (errors.length === 0) {
+ o.onCompleted();
+ } else if (errors.length === 1) {
+ o.onError(errors[0]);
+ } else {
+ o.onError(new CompositeError(errors));
+ }
+ }
+
+ group.add(m);
+
+ m.setDisposable(source.subscribe(
+ function (innerSource) {
+ var innerSubscription = new SingleAssignmentDisposable();
+ group.add(innerSubscription);
+
+ // Check for promises support
+ isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
+
+ innerSubscription.setDisposable(innerSource.subscribe(
+ function (x) { o.onNext(x); },
+ function (e) {
+ errors.push(e);
+ group.remove(innerSubscription);
+ isStopped && group.length === 1 && setCompletion();
+ },
+ function () {
+ group.remove(innerSubscription);
+ isStopped && group.length === 1 && setCompletion();
+ }));
+ },
+ function (e) {
+ errors.push(e);
+ isStopped = true;
+ group.length === 1 && setCompletion();
+ },
+ function () {
+ isStopped = true;
+ group.length === 1 && setCompletion();
+ }));
+ return group;
+ });
+ };
+
+ var MergeAllObservable = (function (__super__) {
+ inherits(MergeAllObservable, __super__);
+
+ function MergeAllObservable(source) {
+ this.source = source;
+ __super__.call(this);
+ }
+
+ MergeAllObservable.prototype.subscribeCore = function (observer) {
+ var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
+ g.add(m);
+ m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
+ return g;
+ };
+
+ function MergeAllObserver(o, g) {
+ this.o = o;
+ this.g = g;
+ this.isStopped = false;
+ this.done = false;
+ }
+ MergeAllObserver.prototype.onNext = function(innerSource) {
+ if(this.isStopped) { return; }
+ var sad = new SingleAssignmentDisposable();
+ this.g.add(sad);
+
+ isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
+
+ sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
+ };
+ MergeAllObserver.prototype.onError = function (e) {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ }
+ };
+ MergeAllObserver.prototype.onCompleted = function () {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.done = true;
+ this.g.length === 1 && this.o.onCompleted();
+ }
+ };
+ MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
+ MergeAllObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ function InnerObserver(parent, g, sad) {
+ this.parent = parent;
+ this.g = g;
+ this.sad = sad;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
+ InnerObserver.prototype.onError = function (e) {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.parent.o.onError(e);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if(!this.isStopped) {
+ var parent = this.parent;
+ this.isStopped = true;
+ parent.g.remove(this.sad);
+ parent.done && parent.g.length === 1 && parent.o.onCompleted();
+ }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.parent.o.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return MergeAllObservable;
+ }(ObservableBase));
+
+ /**
+ * Merges an observable sequence of observable sequences into an observable sequence.
+ * @returns {Observable} The observable sequence that merges the elements of the inner sequences.
+ */
+ observableProto.mergeAll = observableProto.mergeObservable = function () {
+ return new MergeAllObservable(this);
+ };
+
+ /**
+ * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
+ * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
+ * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
+ */
+ observableProto.onErrorResumeNext = function (second) {
+ if (!second) { throw new Error('Second observable is required'); }
+ return onErrorResumeNext([this, second]);
+ };
+
+ /**
+ * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
+ *
+ * @example
+ * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
+ * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
+ * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
+ */
+ var onErrorResumeNext = Observable.onErrorResumeNext = function () {
+ var sources = [];
+ if (Array.isArray(arguments[0])) {
+ sources = arguments[0];
+ } else {
+ for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
+ }
+ return new AnonymousObservable(function (observer) {
+ var pos = 0, subscription = new SerialDisposable(),
+ cancelable = immediateScheduler.scheduleRecursive(function (self) {
+ var current, d;
+ if (pos < sources.length) {
+ current = sources[pos++];
+ isPromise(current) && (current = observableFromPromise(current));
+ d = new SingleAssignmentDisposable();
+ subscription.setDisposable(d);
+ d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
+ } else {
+ observer.onCompleted();
+ }
+ });
+ return new CompositeDisposable(subscription, cancelable);
+ });
+ };
+
+ /**
+ * Returns the values from the source observable sequence only after the other observable sequence produces a value.
+ * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
+ * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
+ */
+ observableProto.skipUntil = function (other) {
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ var isOpen = false;
+ var disposables = new CompositeDisposable(source.subscribe(function (left) {
+ isOpen && o.onNext(left);
+ }, function (e) { o.onError(e); }, function () {
+ isOpen && o.onCompleted();
+ }));
+
+ isPromise(other) && (other = observableFromPromise(other));
+
+ var rightSubscription = new SingleAssignmentDisposable();
+ disposables.add(rightSubscription);
+ rightSubscription.setDisposable(other.subscribe(function () {
+ isOpen = true;
+ rightSubscription.dispose();
+ }, function (e) { o.onError(e); }, function () {
+ rightSubscription.dispose();
+ }));
+
+ return disposables;
+ }, source);
+ };
+
+ var SwitchObservable = (function(__super__) {
+ inherits(SwitchObservable, __super__);
+ function SwitchObservable(source) {
+ this.source = source;
+ __super__.call(this);
+ }
+
+ SwitchObservable.prototype.subscribeCore = function (o) {
+ var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
+ return new CompositeDisposable(s, inner);
+ };
+
+ function SwitchObserver(o, inner) {
+ this.o = o;
+ this.inner = inner;
+ this.stopped = false;
+ this.latest = 0;
+ this.hasLatest = false;
+ this.isStopped = false;
+ }
+ SwitchObserver.prototype.onNext = function (innerSource) {
+ if (this.isStopped) { return; }
+ var d = new SingleAssignmentDisposable(), id = ++this.latest;
+ this.hasLatest = true;
+ this.inner.setDisposable(d);
+ isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
+ d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
+ };
+ SwitchObserver.prototype.onError = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ }
+ };
+ SwitchObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.stopped = true;
+ !this.hasLatest && this.o.onCompleted();
+ }
+ };
+ SwitchObserver.prototype.dispose = function () { this.isStopped = true; };
+ SwitchObserver.prototype.fail = function (e) {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ function InnerObserver(parent, id) {
+ this.parent = parent;
+ this.id = id;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) {
+ if (this.isStopped) { return; }
+ this.parent.latest === this.id && this.parent.o.onNext(x);
+ };
+ InnerObserver.prototype.onError = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.parent.latest === this.id && this.parent.o.onError(e);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ if (this.parent.latest === this.id) {
+ this.parent.hasLatest = false;
+ this.parent.isStopped && this.parent.o.onCompleted();
+ }
+ }
+ };
+ InnerObserver.prototype.dispose = function () { this.isStopped = true; }
+ InnerObserver.prototype.fail = function (e) {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.parent.o.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ return SwitchObservable;
+ }(ObservableBase));
+
+ /**
+ * 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 () {
+ return new SwitchObservable(this);
+ };
+
+ var TakeUntilObservable = (function(__super__) {
+ inherits(TakeUntilObservable, __super__);
+
+ function TakeUntilObservable(source, other) {
+ this.source = source;
+ this.other = isPromise(other) ? observableFromPromise(other) : other;
+ __super__.call(this);
+ }
+
+ TakeUntilObservable.prototype.subscribeCore = function(o) {
+ return new CompositeDisposable(
+ this.source.subscribe(o),
+ this.other.subscribe(new InnerObserver(o))
+ );
+ };
+
+ function InnerObserver(o) {
+ this.o = o;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) {
+ if (this.isStopped) { return; }
+ this.o.onCompleted();
+ };
+ InnerObserver.prototype.onError = function (err) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(err);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ !this.isStopped && (this.isStopped = true);
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ return TakeUntilObservable;
+ }(ObservableBase));
+
+ /**
+ * 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) {
+ return new TakeUntilObservable(this, other);
+ };
+
+ function falseFactory() { return false; }
+
+ /**
+ * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
+ */
+ observableProto.withLatestFrom = function () {
+ var len = arguments.length, args = new Array(len)
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ var resultSelector = args.pop(), source = this;
+ Array.isArray(args[0]) && (args = args[0]);
+
+ return new AnonymousObservable(function (observer) {
+ var n = args.length,
+ hasValue = arrayInitialize(n, falseFactory),
+ hasValueAll = false,
+ values = new Array(n);
+
+ var subscriptions = new Array(n + 1);
+ for (var idx = 0; idx < n; idx++) {
+ (function (i) {
+ var other = args[i], sad = new SingleAssignmentDisposable();
+ isPromise(other) && (other = observableFromPromise(other));
+ sad.setDisposable(other.subscribe(function (x) {
+ values[i] = x;
+ hasValue[i] = true;
+ hasValueAll = hasValue.every(identity);
+ }, function (e) { observer.onError(e); }, noop));
+ subscriptions[i] = sad;
+ }(idx));
+ }
+
+ var sad = new SingleAssignmentDisposable();
+ sad.setDisposable(source.subscribe(function (x) {
+ var allValues = [x].concat(values);
+ if (!hasValueAll) { return; }
+ var res = tryCatch(resultSelector).apply(null, allValues);
+ if (res === errorObj) { return observer.onError(res.e); }
+ observer.onNext(res);
+ }, function (e) { observer.onError(e); }, function () {
+ observer.onCompleted();
+ }));
+ subscriptions[n] = sad;
+
+ return new CompositeDisposable(subscriptions);
+ }, this);
+ };
+
+ function zipArray(second, resultSelector) {
+ var first = this;
+ return new AnonymousObservable(function (o) {
+ var index = 0, len = second.length;
+ return first.subscribe(function (left) {
+ if (index < len) {
+ var right = second[index++], res = tryCatch(resultSelector)(left, right);
+ if (res === errorObj) { return o.onError(res.e); }
+ o.onNext(res);
+ } else {
+ o.onCompleted();
+ }
+ }, function (e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, first);
+ }
+
+ function falseFactory() { return false; }
+ function emptyArrayFactory() { return []; }
+
+ /**
+ * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
+ * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
+ * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
+ */
+ observableProto.zip = function () {
+ if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
+ var len = arguments.length, args = new Array(len);
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+
+ var parent = this, resultSelector = args.pop();
+ args.unshift(parent);
+ return new AnonymousObservable(function (o) {
+ var n = args.length,
+ queues = arrayInitialize(n, emptyArrayFactory),
+ isDone = arrayInitialize(n, falseFactory);
+
+ var subscriptions = new Array(n);
+ for (var idx = 0; idx < n; idx++) {
+ (function (i) {
+ var source = args[i], sad = new SingleAssignmentDisposable();
+ isPromise(source) && (source = observableFromPromise(source));
+ sad.setDisposable(source.subscribe(function (x) {
+ queues[i].push(x);
+ if (queues.every(function (x) { return x.length > 0; })) {
+ var queuedValues = queues.map(function (x) { return x.shift(); }),
+ res = tryCatch(resultSelector).apply(parent, queuedValues);
+ if (res === errorObj) { return o.onError(res.e); }
+ o.onNext(res);
+ } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
+ o.onCompleted();
+ }
+ }, function (e) { o.onError(e); }, function () {
+ isDone[i] = true;
+ isDone.every(identity) && o.onCompleted();
+ }));
+ subscriptions[i] = sad;
+ })(idx);
+ }
+
+ return new CompositeDisposable(subscriptions);
+ }, parent);
+ };
+
+ /**
+ * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
+ * @param arguments Observable sources.
+ * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
+ * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
+ */
+ Observable.zip = function () {
+ var len = arguments.length, args = new Array(len);
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ var first = args.shift();
+ return first.zip.apply(first, args);
+ };
+
+ function falseFactory() { return false; }
+ function arrayFactory() { return []; }
+
+ /**
+ * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
+ * @param arguments Observable sources.
+ * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
+ */
+ Observable.zipArray = function () {
+ var sources;
+ if (Array.isArray(arguments[0])) {
+ sources = arguments[0];
+ } else {
+ var len = arguments.length;
+ sources = new Array(len);
+ for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
+ }
+ return new AnonymousObservable(function (o) {
+ var n = sources.length,
+ queues = arrayInitialize(n, arrayFactory),
+ isDone = arrayInitialize(n, falseFactory);
+
+ 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);
+ if (queues.every(function (x) { return x.length > 0; })) {
+ var res = queues.map(function (x) { return x.shift(); });
+ o.onNext(res);
+ } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
+ return o.onCompleted();
+ }
+ }, function (e) { o.onError(e); }, function () {
+ isDone[i] = true;
+ isDone.every(identity) && o.onCompleted();
+ }));
+ })(idx);
+ }
+
+ return new CompositeDisposable(subscriptions);
+ });
+ };
+
+ /**
+ * Hides the identity of an observable sequence.
+ * @returns {Observable} An observable sequence that hides the identity of the source sequence.
+ */
+ observableProto.asObservable = function () {
+ var source = this;
+ return new AnonymousObservable(function (o) { return source.subscribe(o); }, source);
+ };
+
+ /**
+ * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
+ *
+ * @example
+ * var res = xs.bufferWithCount(10);
+ * var res = xs.bufferWithCount(10, 1);
+ * @param {Number} count Length of each buffer.
+ * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
+ * @returns {Observable} An observable sequence of buffers.
+ */
+ observableProto.bufferWithCount = function (count, skip) {
+ if (typeof skip !== 'number') {
+ skip = count;
+ }
+ return this.windowWithCount(count, skip).selectMany(function (x) {
+ return x.toArray();
+ }).where(function (x) {
+ return x.length > 0;
+ });
+ };
+
+ /**
+ * Dematerializes the explicit notification values of an observable sequence as implicit notifications.
+ * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
+ */
+ observableProto.dematerialize = function () {
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, this);
+ };
+
+ /**
+ * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
+ *
+ * var obs = observable.distinctUntilChanged();
+ * var obs = observable.distinctUntilChanged(function (x) { return x.id; });
+ * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
+ *
+ * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
+ * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
+ * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
+ */
+ observableProto.distinctUntilChanged = function (keySelector, comparer) {
+ var source = this;
+ comparer || (comparer = defaultComparer);
+ return new AnonymousObservable(function (o) {
+ var hasCurrentKey = false, currentKey;
+ return source.subscribe(function (value) {
+ var key = value;
+ if (keySelector) {
+ key = tryCatch(keySelector)(value);
+ if (key === errorObj) { return o.onError(key.e); }
+ }
+ if (hasCurrentKey) {
+ var comparerEquals = tryCatch(comparer)(currentKey, key);
+ if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); }
+ }
+ if (!hasCurrentKey || !comparerEquals) {
+ hasCurrentKey = true;
+ currentKey = key;
+ o.onNext(value);
+ }
+ }, function (e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, this);
+ };
+
+ var TapObservable = (function(__super__) {
+ inherits(TapObservable,__super__);
+ function TapObservable(source, observerOrOnNext, onError, onCompleted) {
+ this.source = source;
+ this.t = !observerOrOnNext || isFunction(observerOrOnNext) ?
+ observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
+ observerOrOnNext;
+ __super__.call(this);
+ }
+
+ TapObservable.prototype.subscribeCore = function(o) {
+ return this.source.subscribe(new InnerObserver(o, this.t));
+ };
+
+ function InnerObserver(o, t) {
+ this.o = o;
+ this.t = t;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function(x) {
+ if (this.isStopped) { return; }
+ var res = tryCatch(this.t.onNext).call(this.t, x);
+ if (res === errorObj) { this.o.onError(res.e); }
+ this.o.onNext(x);
+ };
+ InnerObserver.prototype.onError = function(err) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ var res = tryCatch(this.t.onError).call(this.t, err);
+ if (res === errorObj) { return this.o.onError(res.e); }
+ this.o.onError(err);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function() {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ var res = tryCatch(this.t.onCompleted).call(this.t);
+ if (res === errorObj) { return this.o.onError(res.e); }
+ this.o.onCompleted();
+ }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ return TapObservable;
+ }(ObservableBase));
+
+ /**
+ * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
+ * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
+ * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
+ * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
+ * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
+ * @returns {Observable} The source sequence with the side-effecting behavior applied.
+ */
+ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
+ return new TapObservable(this, observerOrOnNext, onError, onCompleted);
+ };
+
+ /**
+ * Invokes an action for each element in the observable sequence.
+ * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
+ * @param {Function} onNext Action to invoke for each element in the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} The source sequence with the side-effecting behavior applied.
+ */
+ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
+ return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
+ };
+
+ /**
+ * Invokes an action upon exceptional termination of the observable sequence.
+ * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
+ * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} The source sequence with the side-effecting behavior applied.
+ */
+ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
+ return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
+ };
+
+ /**
+ * Invokes an action upon graceful termination of the observable sequence.
+ * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
+ * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} The source sequence with the side-effecting behavior applied.
+ */
+ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
+ return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
+ };
+
+ /**
+ * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
+ * @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
+ * @returns {Observable} Source sequence with the action-invoking termination behavior applied.
+ */
+ observableProto['finally'] = observableProto.ensure = function (action) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var subscription;
+ try {
+ subscription = source.subscribe(observer);
+ } catch (e) {
+ action();
+ throw e;
+ }
+ return disposableCreate(function () {
+ try {
+ subscription.dispose();
+ } catch (e) {
+ throw e;
+ } finally {
+ action();
+ }
+ });
+ }, this);
+ };
+
+ /**
+ * @deprecated use #finally or #ensure instead.
+ */
+ observableProto.finallyAction = function (action) {
+ //deprecate('finallyAction', 'finally or ensure');
+ return this.ensure(action);
+ };
+
+ var IgnoreElementsObservable = (function(__super__) {
+ inherits(IgnoreElementsObservable, __super__);
+
+ function IgnoreElementsObservable(source) {
+ this.source = source;
+ __super__.call(this);
+ }
+
+ IgnoreElementsObservable.prototype.subscribeCore = function (o) {
+ return this.source.subscribe(new InnerObserver(o));
+ };
+
+ function InnerObserver(o) {
+ this.o = o;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = noop;
+ InnerObserver.prototype.onError = function (err) {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(err);
+ }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if(!this.isStopped) {
+ this.isStopped = true;
+ this.o.onCompleted();
+ }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.observer.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return IgnoreElementsObservable;
+ }(ObservableBase));
+
+ /**
+ * 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 () {
+ return new IgnoreElementsObservable(this);
+ };
+
+ /**
+ * Materializes the implicit notifications of an observable sequence as explicit notification values.
+ * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
+ */
+ observableProto.materialize = function () {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ return source.subscribe(function (value) {
+ observer.onNext(notificationCreateOnNext(value));
+ }, function (e) {
+ observer.onNext(notificationCreateOnError(e));
+ observer.onCompleted();
+ }, function () {
+ observer.onNext(notificationCreateOnCompleted());
+ observer.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
+ * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
+ * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
+ */
+ observableProto.repeat = function (repeatCount) {
+ return enumerableRepeat(this, repeatCount).concat();
+ };
+
+ /**
+ * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
+ * Note if you encounter an error and want it to retry once, then you must use .retry(2);
+ *
+ * @example
+ * var res = retried = retry.repeat();
+ * var res = retried = retry.repeat(2);
+ * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
+ * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
+ */
+ observableProto.retry = function (retryCount) {
+ return enumerableRepeat(this, retryCount).catchError();
+ };
+
+ /**
+ * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
+ * if the notifier completes, the observable sequence completes.
+ *
+ * @example
+ * var timer = Observable.timer(500);
+ * var source = observable.retryWhen(timer);
+ * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
+ * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
+ */
+ observableProto.retryWhen = function (notifier) {
+ return enumerableRepeat(this).catchErrorWhen(notifier);
+ };
+ var ScanObservable = (function(__super__) {
+ inherits(ScanObservable, __super__);
+ function ScanObservable(source, accumulator, hasSeed, seed) {
+ this.source = source;
+ this.accumulator = accumulator;
+ this.hasSeed = hasSeed;
+ this.seed = seed;
+ __super__.call(this);
+ }
+
+ ScanObservable.prototype.subscribeCore = function(observer) {
+ return this.source.subscribe(new ScanObserver(observer,this));
+ };
+
+ return ScanObservable;
+ }(ObservableBase));
+
+ function ScanObserver(observer, parent) {
+ this.observer = observer;
+ this.accumulator = parent.accumulator;
+ this.hasSeed = parent.hasSeed;
+ this.seed = parent.seed;
+ this.hasAccumulation = false;
+ this.accumulation = null;
+ this.hasValue = false;
+ this.isStopped = false;
+ }
+ ScanObserver.prototype.onNext = function (x) {
+ if (this.isStopped) { return; }
+ !this.hasValue && (this.hasValue = true);
+ try {
+ if (this.hasAccumulation) {
+ this.accumulation = this.accumulator(this.accumulation, x);
+ } else {
+ this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x;
+ this.hasAccumulation = true;
+ }
+ } catch (e) {
+ return this.observer.onError(e);
+ }
+ this.observer.onNext(this.accumulation);
+ };
+ ScanObserver.prototype.onError = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.observer.onError(e);
+ }
+ };
+ ScanObserver.prototype.onCompleted = function () {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ !this.hasValue && this.hasSeed && this.observer.onNext(this.seed);
+ this.observer.onCompleted();
+ }
+ };
+ ScanObserver.prototype.dispose = function() { this.isStopped = true; };
+ ScanObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.observer.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ /**
+ * 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.
+ * @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 ScanObservable(this, accumulator, hasSeed, seed);
+ };
+
+ /**
+ * Bypasses a specified number of elements at the end of an observable sequence.
+ * @description
+ * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
+ * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
+ * @param count Number of elements to bypass at the end of the source sequence.
+ * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
+ */
+ observableProto.skipLast = function (count) {
+ if (count < 0) { throw new ArgumentOutOfRangeError(); }
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ var q = [];
+ return source.subscribe(function (x) {
+ q.push(x);
+ q.length > count && o.onNext(q.shift());
+ }, function (e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, source);
+ };
+
+ /**
+ * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
+ * @example
+ * var res = source.startWith(1, 2, 3);
+ * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
+ * @param {Arguments} args The specified values to prepend to the observable sequence
+ * @returns {Observable} The source sequence prepended with the specified values.
+ */
+ observableProto.startWith = function () {
+ var values, scheduler, start = 0;
+ if (!!arguments.length && isScheduler(arguments[0])) {
+ scheduler = arguments[0];
+ start = 1;
+ } else {
+ scheduler = immediateScheduler;
+ }
+ for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
+ return enumerableOf([observableFromArray(args, scheduler), this]).concat();
+ };
+
+ /**
+ * Returns a specified number of contiguous elements from the end of an observable sequence.
+ * @description
+ * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
+ * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
+ * @param {Number} count Number of elements to take from the end of the source sequence.
+ * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
+ */
+ observableProto.takeLast = function (count) {
+ if (count < 0) { throw new ArgumentOutOfRangeError(); }
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ var q = [];
+ return source.subscribe(function (x) {
+ q.push(x);
+ q.length > count && q.shift();
+ }, function (e) { o.onError(e); }, function () {
+ while (q.length > 0) { o.onNext(q.shift()); }
+ o.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * Returns an array with the specified number of contiguous elements from the end of an observable sequence.
+ *
+ * @description
+ * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
+ * source sequence, this buffer is produced on the result sequence.
+ * @param {Number} count Number of elements to take from the end of the source sequence.
+ * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
+ */
+ observableProto.takeLastBuffer = function (count) {
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ var q = [];
+ return source.subscribe(function (x) {
+ q.push(x);
+ q.length > count && q.shift();
+ }, function (e) { o.onError(e); }, function () {
+ o.onNext(q);
+ o.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
+ *
+ * var res = xs.windowWithCount(10);
+ * var res = xs.windowWithCount(10, 1);
+ * @param {Number} count Length of each window.
+ * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
+ * @returns {Observable} An observable sequence of windows.
+ */
+ observableProto.windowWithCount = function (count, skip) {
+ var source = this;
+ +count || (count = 0);
+ Math.abs(count) === Infinity && (count = 0);
+ if (count <= 0) { throw new ArgumentOutOfRangeError(); }
+ skip == null && (skip = count);
+ +skip || (skip = 0);
+ Math.abs(skip) === Infinity && (skip = 0);
+
+ if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
+ return new AnonymousObservable(function (observer) {
+ var m = new SingleAssignmentDisposable(),
+ refCountDisposable = new RefCountDisposable(m),
+ n = 0,
+ q = [];
+
+ function createWindow () {
+ var s = new Subject();
+ q.push(s);
+ observer.onNext(addRef(s, refCountDisposable));
+ }
+
+ createWindow();
+
+ m.setDisposable(source.subscribe(
+ function (x) {
+ for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
+ var c = n - count + 1;
+ c >= 0 && c % skip === 0 && q.shift().onCompleted();
+ ++n % skip === 0 && createWindow();
+ },
+ function (e) {
+ while (q.length > 0) { q.shift().onError(e); }
+ observer.onError(e);
+ },
+ function () {
+ while (q.length > 0) { q.shift().onCompleted(); }
+ observer.onCompleted();
+ }
+ ));
+ return refCountDisposable;
+ }, source);
+ };
+
+ function concatMap(source, selector, thisArg) {
+ var selectorFunc = bindCallback(selector, thisArg, 3);
+ return source.map(function (x, i) {
+ var result = selectorFunc(x, i, source);
+ isPromise(result) && (result = observableFromPromise(result));
+ (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
+ return result;
+ }).concatAll();
+ }
+
+ /**
+ * One of the Following:
+ * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
+ *
+ * @example
+ * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
+ * Or:
+ * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
+ *
+ * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
+ * Or:
+ * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
+ *
+ * var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
+ * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
+ * source sequence onto which could be either an observable or Promise.
+ * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
+ */
+ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
+ if (isFunction(selector) && isFunction(resultSelector)) {
+ return this.concatMap(function (x, i) {
+ var selectorResult = selector(x, i);
+ isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
+ (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
+
+ return selectorResult.map(function (y, i2) {
+ return resultSelector(x, y, i, i2);
+ });
+ });
+ }
+ return isFunction(selector) ?
+ concatMap(this, selector, thisArg) :
+ concatMap(this, function () { return selector; });
+ };
+
+ /**
+ * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
+ * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
+ * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
+ * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
+ * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
+ */
+ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
+ var source = this,
+ onNextFunc = bindCallback(onNext, thisArg, 2),
+ onErrorFunc = bindCallback(onError, thisArg, 1),
+ onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
+ return new AnonymousObservable(function (observer) {
+ var index = 0;
+ return source.subscribe(
+ function (x) {
+ var result;
+ try {
+ result = onNextFunc(x, index++);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ },
+ function (err) {
+ var result;
+ try {
+ result = onErrorFunc(err);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ observer.onCompleted();
+ },
+ function () {
+ var result;
+ try {
+ result = onCompletedFunc();
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ observer.onCompleted();
+ });
+ }, this).concatAll();
+ };
+
+ /**
+ * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
+ *
+ * var res = obs = xs.defaultIfEmpty();
+ * 2 - obs = xs.defaultIfEmpty(false);
+ *
+ * @memberOf Observable#
+ * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
+ * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
+ */
+ observableProto.defaultIfEmpty = function (defaultValue) {
+ var source = this;
+ defaultValue === undefined && (defaultValue = null);
+ return new AnonymousObservable(function (observer) {
+ var found = false;
+ return source.subscribe(function (x) {
+ found = true;
+ observer.onNext(x);
+ },
+ function (e) { observer.onError(e); },
+ function () {
+ !found && observer.onNext(defaultValue);
+ observer.onCompleted();
+ });
+ }, source);
+ };
+
+ // Swap out for Array.findIndex
+ function arrayIndexOfComparer(array, item, comparer) {
+ for (var i = 0, len = array.length; i < len; i++) {
+ if (comparer(array[i], item)) { return i; }
+ }
+ return -1;
+ }
+
+ function HashSet(comparer) {
+ this.comparer = comparer;
+ this.set = [];
+ }
+ HashSet.prototype.push = function(value) {
+ var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
+ retValue && this.set.push(value);
+ return retValue;
+ };
+
+ /**
+ * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
+ * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
+ *
+ * @example
+ * var res = obs = xs.distinct();
+ * 2 - obs = xs.distinct(function (x) { return x.id; });
+ * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
+ * @param {Function} [keySelector] A function to compute the comparison key for each element.
+ * @param {Function} [comparer] Used to compare items in the collection.
+ * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
+ */
+ observableProto.distinct = function (keySelector, comparer) {
+ var source = this;
+ comparer || (comparer = defaultComparer);
+ return new AnonymousObservable(function (o) {
+ var hashSet = new HashSet(comparer);
+ return source.subscribe(function (x) {
+ var key = x;
+
+ if (keySelector) {
+ try {
+ key = keySelector(x);
+ } catch (e) {
+ o.onError(e);
+ return;
+ }
+ }
+ hashSet.push(key) && o.onNext(x);
+ },
+ function (e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, this);
+ };
+
+ var MapObservable = (function (__super__) {
+ inherits(MapObservable, __super__);
+
+ function MapObservable(source, selector, thisArg) {
+ this.source = source;
+ this.selector = bindCallback(selector, thisArg, 3);
+ __super__.call(this);
+ }
+
+ function innerMap(selector, self) {
+ return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }
+ }
+
+ MapObservable.prototype.internalMap = function (selector, thisArg) {
+ return new MapObservable(this.source, innerMap(selector, this), thisArg);
+ };
+
+ MapObservable.prototype.subscribeCore = function (o) {
+ return this.source.subscribe(new InnerObserver(o, this.selector, this));
+ };
+
+ function InnerObserver(o, selector, source) {
+ this.o = o;
+ this.selector = selector;
+ this.source = source;
+ this.i = 0;
+ this.isStopped = false;
+ }
+
+ InnerObserver.prototype.onNext = function(x) {
+ if (this.isStopped) { return; }
+ var result = tryCatch(this.selector)(x, this.i++, this.source);
+ if (result === errorObj) {
+ return this.o.onError(result.e);
+ }
+ this.o.onNext(result);
+ };
+ InnerObserver.prototype.onError = function (e) {
+ if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
+ };
+ InnerObserver.prototype.onCompleted = function () {
+ if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function (e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+
+ return false;
+ };
+
+ return MapObservable;
+
+ }(ObservableBase));
+
+ /**
+ * Projects each element of an observable sequence into a new form by incorporating the element's index.
+ * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
+ */
+ observableProto.map = observableProto.select = function (selector, thisArg) {
+ var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
+ return this instanceof MapObservable ?
+ this.internalMap(selectorFn, thisArg) :
+ new MapObservable(this, selectorFn, thisArg);
+ };
+
+ /**
+ * Retrieves the value of a specified nested property from all elements in
+ * the Observable sequence.
+ * @param {Arguments} arguments The nested properties to pluck.
+ * @returns {Observable} Returns a new Observable sequence of property values.
+ */
+ observableProto.pluck = function () {
+ var args = arguments, len = arguments.length;
+ if (len === 0) { throw new Error('List of properties cannot be empty.'); }
+ return this.map(function (x) {
+ var currentProp = x;
+ for (var i = 0; i < len; i++) {
+ var p = currentProp[args[i]];
+ if (typeof p !== 'undefined') {
+ currentProp = p;
+ } else {
+ return undefined;
+ }
+ }
+ return currentProp;
+ });
+ };
+
+ /**
+ * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
+ * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
+ * @param {Function} onError A transform function to apply when an error occurs in the source sequence.
+ * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
+ * @param {Any} [thisArg] An optional "this" to use to invoke each transform.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
+ */
+ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var index = 0;
+
+ return source.subscribe(
+ function (x) {
+ var result;
+ try {
+ result = onNext.call(thisArg, x, index++);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ },
+ function (err) {
+ var result;
+ try {
+ result = onError.call(thisArg, err);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ observer.onCompleted();
+ },
+ function () {
+ var result;
+ try {
+ result = onCompleted.call(thisArg);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ isPromise(result) && (result = observableFromPromise(result));
+ observer.onNext(result);
+ observer.onCompleted();
+ });
+ }, source).mergeAll();
+ };
+
+ function flatMap(source, selector, thisArg) {
+ var selectorFunc = bindCallback(selector, thisArg, 3);
+ return source.map(function (x, i) {
+ var result = selectorFunc(x, i, source);
+ isPromise(result) && (result = observableFromPromise(result));
+ (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
+ return result;
+ }).mergeAll();
+ }
+
+ /**
+ * One of the Following:
+ * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
+ *
+ * @example
+ * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
+ * Or:
+ * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
+ *
+ * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
+ * Or:
+ * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
+ *
+ * var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
+ * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
+ * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
+ */
+ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
+ if (isFunction(selector) && isFunction(resultSelector)) {
+ return this.flatMap(function (x, i) {
+ var selectorResult = selector(x, i);
+ isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
+ (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
+
+ return selectorResult.map(function (y, i2) {
+ return resultSelector(x, y, i, i2);
+ });
+ }, thisArg);
+ }
+ return isFunction(selector) ?
+ flatMap(this, selector, thisArg) :
+ flatMap(this, function () { return selector; });
+ };
+
+ /**
+ * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
+ * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
+ * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
+ * and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
+ */
+ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
+ return this.select(selector, thisArg).switchLatest();
+ };
+
+ var SkipObservable = (function(__super__) {
+ inherits(SkipObservable, __super__);
+ function SkipObservable(source, count) {
+ this.source = source;
+ this.skipCount = count;
+ __super__.call(this);
+ }
+
+ SkipObservable.prototype.subscribeCore = function (o) {
+ return this.source.subscribe(new InnerObserver(o, this.skipCount));
+ };
+
+ function InnerObserver(o, c) {
+ this.c = c;
+ this.r = c;
+ this.o = o;
+ this.isStopped = false;
+ }
+ InnerObserver.prototype.onNext = function (x) {
+ if (this.isStopped) { return; }
+ if (this.r <= 0) {
+ this.o.onNext(x);
+ } else {
+ this.r--;
+ }
+ };
+ InnerObserver.prototype.onError = function(e) {
+ if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
+ };
+ InnerObserver.prototype.onCompleted = function() {
+ if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
+ };
+ InnerObserver.prototype.dispose = function() { this.isStopped = true; };
+ InnerObserver.prototype.fail = function(e) {
+ if (!this.isStopped) {
+ this.isStopped = true;
+ this.o.onError(e);
+ return true;
+ }
+ return false;
+ };
+
+ return SkipObservable;
+ }(ObservableBase));
+
+ /**
+ * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
+ * @param {Number} count The number of elements to skip before returning the remaining elements.
+ * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
+ */
+ observableProto.skip = function (count) {
+ if (count < 0) { throw new ArgumentOutOfRangeError(); }
+ return new SkipObservable(this, count);
+ };
+ /**
+ * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
+ * The element's index is used in the logic of the predicate function.
+ *
+ * var res = source.skipWhile(function (value) { return value < 10; });
+ * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
+ * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
+ * @param {Any} [thisArg] Object to use as this when executing callback.
+ * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
+ */
+ observableProto.skipWhile = function (predicate, thisArg) {
+ var source = this,
+ callback = bindCallback(predicate, thisArg, 3);
+ return new AnonymousObservable(function (o) {
+ var i = 0, running = false;
+ return source.subscribe(function (x) {
+ if (!running) {
+ try {
+ running = !callback(x, i++, source);
+ } catch (e) {
+ o.onError(e);
+ return;
+ }
+ }
+ running && o.onNext(x);
+ }, function (e) { o.onError(e); }, function () { o.onCompleted(); });
+ }, source);
+ };
+
+ /**
+ * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
+ *
+ * var res = source.take(5);
+ * var res = source.take(0, Rx.Scheduler.timeout);
+ * @param {Number} count The number of elements to return.
+ * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 2) {
+ for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
+ }
+
+ if (err) {
+ try {
+ ret = gen[throwString](err);
+ } catch (e) {
+ return exit(e);
+ }
+ }
+
+ if (!err) {
+ try {
+ ret = gen.next(res);
+ } catch (e) {
+ return exit(e);
+ }
+ }
+
+ if (ret.done) {
+ return exit(null, ret.value);
+ }
+
+ ret.value = toThunk(ret.value, ctx);
+
+ if (typeof ret.value === fnString) {
+ var called = false;
+ try {
+ ret.value.call(ctx, function() {
+ if (called) {
+ return;
+ }
+
+ called = true;
+ next.apply(ctx, arguments);
+ });
+ } catch (e) {
+ timeoutScheduler.schedule(function () {
+ if (called) {
+ return;
+ }
+
+ called = true;
+ next.call(ctx, e);
+ });
+ }
+ return;
+ }
+
+ // Not supported
+ next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
+ }
+ }
+ };
+
+ function handleError(err) {
+ if (!err) { return; }
+ timeoutScheduler.schedule(function() {
+ throw err;
+ });
+ }
+
+ /**
+ * 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.
+ * @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 len = arguments.length, args = new Array(len)
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+
+ return new AnonymousObservable(function (observer) {
+ function handler() {
+ var len = arguments.length, results = new Array(len);
+ for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
+
+ if (selector) {
+ try {
+ results = selector.apply(context, results);
+ } catch (e) {
+ return observer.onError(e);
+ }
+
+ observer.onNext(results);
+ } else {
+ if (results.length <= 1) {
+ observer.onNext.apply(observer, results);
+ } else {
+ observer.onNext(results);
+ }
+ }
+
+ observer.onCompleted();
+ }
+
+ args.push(handler);
+ func.apply(context, args);
+ }).publishLast().refCount();
+ };
+ };
+
+ /**
+ * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
+ * @param {Function} func The function to call
+ * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
+ * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
+ * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
+ */
+ Observable.fromNodeCallback = function (func, context, selector) {
+ return function () {
+ var len = arguments.length, args = new Array(len);
+ for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
+
+ return new AnonymousObservable(function (observer) {
+ function handler(err) {
+ if (err) {
+ observer.onError(err);
+ return;
+ }
+
+ var len = arguments.length, results = [];
+ for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
+
+ if (selector) {
+ try {
+ results = selector.apply(context, results);
+ } catch (e) {
+ return observer.onError(e);
+ }
+ observer.onNext(results);
+ } else {
+ if (results.length <= 1) {
+ observer.onNext.apply(observer, results);
+ } else {
+ observer.onNext(results);
+ }
+ }
+
+ observer.onCompleted();
+ }
+
+ args.push(handler);
+ func.apply(context, args);
+ }).publishLast().refCount();
+ };
+ };
+
+ function 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 or HTMLCollection
+ var toStr = Object.prototype.toString;
+ if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') {
+ 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;
+
+ /**
+ * 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) {
+ // Handles jq, Angular.js, Zepto, Marionette, Ember.js
+ if (typeof element.on === 'function' && typeof element.off === 'function') {
+ return fromEventPattern(
+ function (h) { element.on(eventName, h); },
+ function (h) { element.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) {
+ return observer.onError(err);
+ }
+ }
+
+ 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) {
+ return observer.onError(err);
+ }
+ }
+ 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);
+ }
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 30 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // References
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ AbstractObserver = Rx.internals.AbstractObserver,
+ CompositeDisposable = Rx.CompositeDisposable,
+ Notification = Rx.Notification,
+ Subject = Rx.Subject,
+ Observer = Rx.Observer,
+ disposableEmpty = Rx.Disposable.empty,
+ disposableCreate = Rx.Disposable.create,
+ inherits = Rx.internals.inherits,
+ addProperties = Rx.internals.addProperties,
+ timeoutScheduler = Rx.Scheduler.timeout,
+ currentThreadScheduler = Rx.Scheduler.currentThread,
+ identity = Rx.helpers.identity,
+ isScheduler = Rx.Scheduler.isScheduler,
+ isFunction = Rx.helpers.isFunction,
+ checkDisposed = Rx.Disposable.checkDisposed;
+
+ var errorObj = {e: {}};
+ var tryCatchTarget;
+ function tryCatcher() {
+ try {
+ return tryCatchTarget.apply(this, arguments);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+ }
+ function tryCatch(fn) {
+ if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
+ tryCatchTarget = fn;
+ return tryCatcher;
+ }
+ function thrower(e) {
+ throw e;
+ }
+
+ /**
+ * Used to pause and resume streams.
+ */
+ Rx.Pauser = (function (__super__) {
+ inherits(Pauser, __super__);
+
+ function Pauser() {
+ __super__.call(this);
+ }
+
+ /**
+ * Pauses the underlying sequence.
+ */
+ Pauser.prototype.pause = function () { this.onNext(false); };
+
+ /**
+ * Resumes the underlying sequence.
+ */
+ Pauser.prototype.resume = function () { this.onNext(true); };
+
+ return Pauser;
+ }(Subject));
+
+ var PausableObservable = (function (__super__) {
+
+ inherits(PausableObservable, __super__);
+
+ function subscribe(observer) {
+ var conn = this.source.publish(),
+ subscription = conn.subscribe(observer),
+ connection = disposableEmpty;
+
+ var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
+ if (b) {
+ connection = conn.connect();
+ } else {
+ connection.dispose();
+ connection = disposableEmpty;
+ }
+ });
+
+ return new CompositeDisposable(subscription, connection, pausable);
+ }
+
+ function PausableObservable(source, pauser) {
+ this.source = source;
+ this.controller = new Subject();
+
+ if (pauser && pauser.subscribe) {
+ this.pauser = this.controller.merge(pauser);
+ } else {
+ this.pauser = this.controller;
+ }
+
+ __super__.call(this, subscribe, source);
+ }
+
+ PausableObservable.prototype.pause = function () {
+ this.controller.onNext(false);
+ };
+
+ PausableObservable.prototype.resume = function () {
+ this.controller.onNext(true);
+ };
+
+ return PausableObservable;
+
+ }(Observable));
+
+ /**
+ * Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
+ * @example
+ * var pauser = new Rx.Subject();
+ * var source = Rx.Observable.interval(100).pausable(pauser);
+ * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
+ * @returns {Observable} The observable sequence which is paused based upon the pauser.
+ */
+ observableProto.pausable = function (pauser) {
+ return new PausableObservable(this, pauser);
+ };
+
+ function combineLatestSource(source, subject, resultSelector) {
+ return new AnonymousObservable(function (o) {
+ var hasValue = [false, false],
+ hasValueAll = false,
+ isDone = false,
+ values = new Array(2),
+ err;
+
+ function next(x, i) {
+ values[i] = x
+ hasValue[i] = true;
+ if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
+ if (err) { return o.onError(err); }
+ var res = tryCatch(resultSelector).apply(null, values);
+ if (res === errorObj) { return o.onError(res.e); }
+ o.onNext(res);
+ }
+ isDone && values[1] && o.onCompleted();
+ }
+
+ return new CompositeDisposable(
+ source.subscribe(
+ function (x) {
+ next(x, 0);
+ },
+ function (e) {
+ if (values[1]) {
+ o.onError(e);
+ } else {
+ err = e;
+ }
+ },
+ function () {
+ isDone = true;
+ values[1] && o.onCompleted();
+ }),
+ subject.subscribe(
+ function (x) {
+ next(x, 1);
+ },
+ function (e) { o.onError(e); },
+ function () {
+ isDone = true;
+ next(true, 1);
+ })
+ );
+ }, source);
+ }
+
+ var PausableBufferedObservable = (function (__super__) {
+
+ inherits(PausableBufferedObservable, __super__);
+
+ function subscribe(o) {
+ var q = [], previousShouldFire;
+
+ function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
+
+ var subscription =
+ combineLatestSource(
+ this.source,
+ this.pauser.distinctUntilChanged().startWith(false),
+ function (data, shouldFire) {
+ return { data: data, shouldFire: shouldFire };
+ })
+ .subscribe(
+ function (results) {
+ if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
+ previousShouldFire = results.shouldFire;
+ // change in shouldFire
+ if (results.shouldFire) { drainQueue(); }
+ } else {
+ previousShouldFire = results.shouldFire;
+ // new data
+ if (results.shouldFire) {
+ o.onNext(results.data);
+ } else {
+ q.push(results.data);
+ }
+ }
+ },
+ function (err) {
+ drainQueue();
+ o.onError(err);
+ },
+ function () {
+ drainQueue();
+ o.onCompleted();
+ }
+ );
+ return subscription;
+ }
+
+ function PausableBufferedObservable(source, pauser) {
+ this.source = source;
+ this.controller = new Subject();
+
+ if (pauser && pauser.subscribe) {
+ this.pauser = this.controller.merge(pauser);
+ } else {
+ this.pauser = this.controller;
+ }
+
+ __super__.call(this, subscribe, source);
+ }
+
+ PausableBufferedObservable.prototype.pause = function () {
+ this.controller.onNext(false);
+ };
+
+ PausableBufferedObservable.prototype.resume = function () {
+ this.controller.onNext(true);
+ };
+
+ return PausableBufferedObservable;
+
+ }(Observable));
+
+ /**
+ * Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
+ * and yields the values that were buffered while paused.
+ * @example
+ * var pauser = new Rx.Subject();
+ * var source = Rx.Observable.interval(100).pausableBuffered(pauser);
+ * @param {Observable} pauser The observable sequence used to pause the underlying sequence.
+ * @returns {Observable} The observable sequence which is paused based upon the pauser.
+ */
+ observableProto.pausableBuffered = function (subject) {
+ return new PausableBufferedObservable(this, subject);
+ };
+
+ var ControlledObservable = (function (__super__) {
+
+ inherits(ControlledObservable, __super__);
+
+ function subscribe (observer) {
+ return this.source.subscribe(observer);
+ }
+
+ function ControlledObservable (source, enableQueue, scheduler) {
+ __super__.call(this, subscribe, source);
+ this.subject = new ControlledSubject(enableQueue, scheduler);
+ this.source = source.multicast(this.subject).refCount();
+ }
+
+ ControlledObservable.prototype.request = function (numberOfItems) {
+ return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
+ };
+
+ return ControlledObservable;
+
+ }(Observable));
+
+ var ControlledSubject = (function (__super__) {
+
+ function subscribe (observer) {
+ return this.subject.subscribe(observer);
+ }
+
+ inherits(ControlledSubject, __super__);
+
+ function ControlledSubject(enableQueue, scheduler) {
+ 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.scheduler = scheduler || currentThreadScheduler;
+ }
+
+ addProperties(ControlledSubject.prototype, Observer, {
+ onCompleted: function () {
+ this.hasCompleted = true;
+ if (!this.enableQueue || this.queue.length === 0) {
+ this.subject.onCompleted();
+ } else {
+ this.queue.push(Notification.createOnCompleted());
+ }
+ },
+ onError: function (error) {
+ this.hasFailed = true;
+ this.error = error;
+ if (!this.enableQueue || this.queue.length === 0) {
+ this.subject.onError(error);
+ } else {
+ this.queue.push(Notification.createOnError(error));
+ }
+ },
+ onNext: function (value) {
+ var hasRequested = false;
+
+ if (this.requestedCount === 0) {
+ this.enableQueue && this.queue.push(Notification.createOnNext(value));
+ } else {
+ (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
+ hasRequested = true;
+ }
+ hasRequested && this.subject.onNext(value);
+ },
+ _processRequest: function (numberOfItems) {
+ if (this.enableQueue) {
+ while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
+ (this.queue.length > 0 && this.queue[0].kind !== 'N')) {
+ var first = this.queue.shift();
+ first.accept(this.subject);
+ if (first.kind === 'N') {
+ numberOfItems--;
+ } else {
+ this.disposeCurrentRequest();
+ this.queue = [];
+ }
+ }
+
+ return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
+ }
+
+ return { numberOfItems: numberOfItems, returnValue: false };
+ },
+ request: function (number) {
+ this.disposeCurrentRequest();
+ var self = this;
+
+ this.requestedDisposable = this.scheduler.scheduleWithState(number,
+ function(s, i) {
+ var r = self._processRequest(i), remaining = r.numberOfItems;
+ if (!r.returnValue) {
+ self.requestedCount = remaining;
+ self.requestedDisposable = disposableCreate(function () {
+ self.requestedCount = 0;
+ });
+ }
+ });
+
+ return this.requestedDisposable;
+ },
+ disposeCurrentRequest: function () {
+ this.requestedDisposable.dispose();
+ this.requestedDisposable = disposableEmpty;
+ }
+ });
+
+ return ControlledSubject;
+ }(Observable));
+
+ /**
+ * 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 {bool} enableQueue truthy value to determine if values should be queued pending the next request
+ * @param {Scheduler} scheduler determines how the requests will be scheduled
+ * @returns {Observable} The observable sequence which only propagates values on request.
+ */
+ observableProto.controlled = function (enableQueue, scheduler) {
+
+ if (enableQueue && isScheduler(enableQueue)) {
+ scheduler = enableQueue;
+ enableQueue = true;
+ }
+
+ if (enableQueue == null) { enableQueue = true; }
+ return new ControlledObservable(this, enableQueue, scheduler);
+ };
+
+ var StopAndWaitObservable = (function (__super__) {
+
+ function subscribe (observer) {
+ this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
+
+ var self = this;
+ timeoutScheduler.schedule(function () { self.source.request(1); });
+
+ return this.subscription;
+ }
+
+ inherits(StopAndWaitObservable, __super__);
+
+ function StopAndWaitObservable (source) {
+ __super__.call(this, subscribe, source);
+ this.source = source;
+ }
+
+ var StopAndWaitObserver = (function (__sub__) {
+
+ inherits(StopAndWaitObserver, __sub__);
+
+ function StopAndWaitObserver (observer, observable, cancel) {
+ __sub__.call(this);
+ this.observer = observer;
+ this.observable = observable;
+ this.cancel = cancel;
+ }
+
+ var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
+
+ stopAndWaitObserverProto.completed = function () {
+ this.observer.onCompleted();
+ this.dispose();
+ };
+
+ stopAndWaitObserverProto.error = function (error) {
+ this.observer.onError(error);
+ this.dispose();
+ }
+
+ stopAndWaitObserverProto.next = function (value) {
+ this.observer.onNext(value);
+
+ var self = this;
+ timeoutScheduler.schedule(function () {
+ self.observable.source.request(1);
+ });
+ };
+
+ stopAndWaitObserverProto.dispose = function () {
+ this.observer = null;
+ if (this.cancel) {
+ this.cancel.dispose();
+ this.cancel = null;
+ }
+ __sub__.prototype.dispose.call(this);
+ };
+
+ return StopAndWaitObserver;
+ }(AbstractObserver));
+
+ return StopAndWaitObservable;
+ }(Observable));
+
+
+ /**
+ * Attaches a stop and wait observable to the current observable.
+ * @returns {Observable} A stop and wait observable.
+ */
+ ControlledObservable.prototype.stopAndWait = function () {
+ return new StopAndWaitObservable(this);
+ };
+
+ var WindowedObservable = (function (__super__) {
+
+ function subscribe (observer) {
+ this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
+
+ var self = this;
+ timeoutScheduler.schedule(function () {
+ self.source.request(self.windowSize);
+ });
+
+ return this.subscription;
+ }
+
+ inherits(WindowedObservable, __super__);
+
+ function WindowedObservable(source, windowSize) {
+ __super__.call(this, subscribe, source);
+ this.source = source;
+ this.windowSize = windowSize;
+ }
+
+ var WindowedObserver = (function (__sub__) {
+
+ inherits(WindowedObserver, __sub__);
+
+ function WindowedObserver(observer, observable, cancel) {
+ this.observer = observer;
+ this.observable = observable;
+ this.cancel = cancel;
+ this.received = 0;
+ }
+
+ var windowedObserverPrototype = WindowedObserver.prototype;
+
+ windowedObserverPrototype.completed = function () {
+ this.observer.onCompleted();
+ this.dispose();
+ };
+
+ windowedObserverPrototype.error = function (error) {
+ this.observer.onError(error);
+ this.dispose();
+ };
+
+ windowedObserverPrototype.next = function (value) {
+ this.observer.onNext(value);
+
+ this.received = ++this.received % this.observable.windowSize;
+ if (this.received === 0) {
+ var self = this;
+ timeoutScheduler.schedule(function () {
+ self.observable.source.request(self.observable.windowSize);
+ });
+ }
+ };
+
+ windowedObserverPrototype.dispose = function () {
+ this.observer = null;
+ if (this.cancel) {
+ this.cancel.dispose();
+ this.cancel = null;
+ }
+ __sub__.prototype.dispose.call(this);
+ };
+
+ return WindowedObserver;
+ }(AbstractObserver));
+
+ return WindowedObservable;
+ }(Observable));
+
+ /**
+ * Creates a sliding windowed observable based upon the window size.
+ * @param {Number} windowSize The number of items in the window
+ * @returns {Observable} A windowed observable based upon the window size.
+ */
+ ControlledObservable.prototype.windowed = function (windowSize) {
+ return new WindowedObservable(this, windowSize);
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 31 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ Subject = Rx.Subject,
+ AsyncSubject = Rx.AsyncSubject,
+ Observer = Rx.Observer,
+ ScheduledObserver = Rx.internals.ScheduledObserver,
+ disposableCreate = Rx.Disposable.create,
+ disposableEmpty = Rx.Disposable.empty,
+ CompositeDisposable = Rx.CompositeDisposable,
+ currentThreadScheduler = Rx.Scheduler.currentThread,
+ isFunction = Rx.helpers.isFunction,
+ inherits = Rx.internals.inherits,
+ addProperties = Rx.internals.addProperties,
+ checkDisposed = Rx.Disposable.checkDisposed;
+
+ // Utilities
+ function cloneArray(arr) {
+ var len = arr.length, a = new Array(len);
+ for(var i = 0; i < len; i++) { a[i] = arr[i]; }
+ return a;
+ }
+
+ /**
+ * 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 0; },
+ /**
+ * Notifies all subscribed observers about the end of the sequence.
+ */
+ onCompleted: function () {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ this.isStopped = true;
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ os[i].onCompleted();
+ }
+
+ this.observers.length = 0;
+ },
+ /**
+ * Notifies all subscribed observers about the exception.
+ * @param {Mixed} error The exception to send to all observers.
+ */
+ onError: function (error) {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ this.isStopped = true;
+ this.hasError = true;
+ this.error = error;
+
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ os[i].onError(error);
+ }
+
+ this.observers.length = 0;
+ },
+ /**
+ * Notifies all subscribed observers about the arrival of the specified element in the sequence.
+ * @param {Mixed} value The value to send to all observers.
+ */
+ onNext: function (value) {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ this.value = value;
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ os[i].onNext(value);
+ }
+ },
+ /**
+ * Unsubscribe all observers and release resources.
+ */
+ dispose: function () {
+ this.isDisposed = true;
+ this.observers = null;
+ 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__) {
+
+ var maxSafeInteger = Math.pow(2, 53) - 1;
+
+ function createRemovableDisposable(subject, observer) {
+ return disposableCreate(function () {
+ observer.dispose();
+ !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
+ });
+ }
+
+ function subscribe(observer) {
+ var so = new ScheduledObserver(this.scheduler, observer),
+ subscription = createRemovableDisposable(this, so);
+ checkDisposed(this);
+ this._trim(this.scheduler.now());
+ this.observers.push(so);
+
+ for (var i = 0, len = this.q.length; i < len; i++) {
+ so.onNext(this.q[i].value);
+ }
+
+ if (this.hasError) {
+ so.onError(this.error);
+ } else if (this.isStopped) {
+ so.onCompleted();
+ }
+
+ so.ensureActive();
+ 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 ? maxSafeInteger : bufferSize;
+ this.windowSize = windowSize == null ? maxSafeInteger : 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.prototype, {
+ /**
+ * Indicates whether the subject has observers subscribed to it.
+ * @returns {Boolean} Indicates whether the subject has observers subscribed to it.
+ */
+ hasObservers: function () {
+ return this.observers.length > 0;
+ },
+ _trim: function (now) {
+ while (this.q.length > this.bufferSize) {
+ this.q.shift();
+ }
+ while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
+ this.q.shift();
+ }
+ },
+ /**
+ * Notifies all subscribed observers about the arrival of the specified element in the sequence.
+ * @param {Mixed} value The value to send to all observers.
+ */
+ onNext: function (value) {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ var now = this.scheduler.now();
+ this.q.push({ interval: now, value: value });
+ this._trim(now);
+
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ var observer = os[i];
+ observer.onNext(value);
+ observer.ensureActive();
+ }
+ },
+ /**
+ * Notifies all subscribed observers about the exception.
+ * @param {Mixed} error The exception to send to all observers.
+ */
+ onError: function (error) {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ this.isStopped = true;
+ this.error = error;
+ this.hasError = true;
+ var now = this.scheduler.now();
+ this._trim(now);
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ var observer = os[i];
+ observer.onError(error);
+ observer.ensureActive();
+ }
+ this.observers.length = 0;
+ },
+ /**
+ * Notifies all subscribed observers about the end of the sequence.
+ */
+ onCompleted: function () {
+ checkDisposed(this);
+ if (this.isStopped) { return; }
+ this.isStopped = true;
+ var now = this.scheduler.now();
+ this._trim(now);
+ for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
+ var observer = os[i];
+ observer.onCompleted();
+ observer.ensureActive();
+ }
+ this.observers.length = 0;
+ },
+ /**
+ * 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, function (o) { return subject.subscribe(o); });
+ }
+
+ 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));
+
+ /**
+ * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
+ * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
+ * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
+ */
+ observableProto.singleInstance = function() {
+ var source = this, hasObservable = false, observable;
+
+ function getObservable() {
+ if (!hasObservable) {
+ hasObservable = true;
+ observable = source.finally(function() { hasObservable = false; }).publish().refCount();
+ }
+ return observable;
+ };
+
+ return new AnonymousObservable(function(o) {
+ return getObservable().subscribe(o);
+ });
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 32 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ var Observable = Rx.Observable,
+ CompositeDisposable = Rx.CompositeDisposable,
+ RefCountDisposable = Rx.RefCountDisposable,
+ SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
+ SerialDisposable = Rx.SerialDisposable,
+ Subject = Rx.Subject,
+ observableProto = Observable.prototype,
+ observableEmpty = Observable.empty,
+ observableNever = Observable.never,
+ AnonymousObservable = Rx.AnonymousObservable,
+ observerCreate = Rx.Observer.create,
+ addRef = Rx.internals.addRef,
+ defaultComparer = Rx.internals.isEqual,
+ inherits = Rx.internals.inherits,
+ noop = Rx.helpers.noop,
+ identity = Rx.helpers.identity,
+ isPromise = Rx.helpers.isPromise,
+ observableFromPromise = Observable.fromPromise,
+ ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
+
+ 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 valueOf === 'string') { return stringHashFn(valueOf); }
+ }
+ if (obj.hashCode) { return obj.hashCode(); }
+
+ var id = 17 * uniqueIdCounter++;
+ obj.hashCode = 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 ArgumentOutOfRangeError(); }
+ 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) {
+ 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;
+ }, left);
+ };
+
+ /**
+ * 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;
+ }, left);
+ };
+
+ /**
+ * 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 observableWindowWithBoundaries.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, observableEmpty, function (_, win) {
+ return win;
+ });
+ }
+
+ function observableWindowWithBoundaries(windowBoundaries) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var win = new Subject(),
+ d = new CompositeDisposable(),
+ r = new RefCountDisposable(d);
+
+ observer.onNext(addRef(win, r));
+
+ d.add(source.subscribe(function (x) {
+ win.onNext(x);
+ }, function (err) {
+ win.onError(err);
+ observer.onError(err);
+ }, function () {
+ win.onCompleted();
+ observer.onCompleted();
+ }));
+
+ isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
+
+ d.add(windowBoundaries.subscribe(function (w) {
+ win.onCompleted();
+ win = new Subject();
+ observer.onNext(addRef(win, r));
+ }, function (err) {
+ win.onError(err);
+ observer.onError(err);
+ }, function () {
+ win.onCompleted();
+ observer.onCompleted();
+ }));
+
+ return r;
+ }, source);
+ }
+
+ function observableWindowWithClosingSelector(windowClosingSelector) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var m = new SerialDisposable(),
+ d = new CompositeDisposable(m),
+ r = new RefCountDisposable(d),
+ win = new Subject();
+ observer.onNext(addRef(win, r));
+ d.add(source.subscribe(function (x) {
+ win.onNext(x);
+ }, function (err) {
+ win.onError(err);
+ observer.onError(err);
+ }, function () {
+ win.onCompleted();
+ observer.onCompleted();
+ }));
+
+ function createWindowClose () {
+ var windowClose;
+ try {
+ windowClose = windowClosingSelector();
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+
+ isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
+
+ var m1 = new SingleAssignmentDisposable();
+ m.setDisposable(m1);
+ m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
+ win.onError(err);
+ observer.onError(err);
+ }, function () {
+ win.onCompleted();
+ win = new Subject();
+ observer.onNext(addRef(win, r));
+ createWindowClose();
+ }));
+ }
+
+ createWindowClose();
+ return r;
+ }, source);
+ }
+
+ /**
+ * 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));
+ }, source);
+ };
+
+ /**
+ * 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) {
+ return [
+ this.filter(predicate, thisArg),
+ this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
+ ];
+ };
+
+ /**
+ * 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;
+ }, source);
+ };
+
+ var GroupedObservable = (function (__super__) {
+ inherits(GroupedObservable, __super__);
+
+ function subscribe(observer) {
+ return this.underlyingObservable.subscribe(observer);
+ }
+
+ 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));
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 33 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // Aliases
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ observableThrow = Observable.throwError,
+ observerCreate = Rx.Observer.create,
+ SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
+ CompositeDisposable = Rx.CompositeDisposable,
+ AbstractObserver = Rx.internals.AbstractObserver,
+ noop = Rx.helpers.noop,
+ defaultComparer = Rx.internals.isEqual,
+ inherits = Rx.internals.inherits,
+ Enumerable = Rx.internals.Enumerable,
+ Enumerator = Rx.internals.Enumerator,
+ $iterator$ = Rx.iterator,
+ doneEnumerator = Rx.doneEnumerator;
+
+ /** @private */
+ var Map = root.Map || (function () {
+
+ function Map() {
+ this._keys = [];
+ this._values = [];
+ }
+
+ Map.prototype.get = function (key) {
+ var i = this._keys.indexOf(key);
+ return i !== -1 ? this._values[i] : undefined;
+ };
+
+ Map.prototype.set = function (key, value) {
+ var i = this._keys.indexOf(key);
+ i !== -1 && (this._values[i] = value);
+ this._values[this._keys.push(key) - 1] = value;
+ };
+
+ Map.prototype.forEach = function (callback, thisArg) {
+ for (var i = 0, len = this._keys.length; i < len; i++) {
+ callback.call(thisArg, this._values[i], this._keys[i]);
+ }
+ };
+
+ 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} Pattern object that matches when all observable sequences in the pattern have an available value.
+ */
+ Pattern.prototype.and = function (other) {
+ return new Pattern(this.patterns.concat(other));
+ };
+
+ /**
+ * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
+ * @param {Function} 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} 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 (e) {
+ observer.onError(e);
+ 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;
+ }
+
+ function ActivePlan(joinObserverArray, onNext, onCompleted) {
+ this.joinObserverArray = joinObserverArray;
+ this.onNext = onNext;
+ this.onCompleted = onCompleted;
+ this.joinObservers = new Map();
+ for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
+ var joinObserver = this.joinObserverArray[i];
+ this.joinObservers.set(joinObserver, joinObserver);
+ }
+ }
+
+ ActivePlan.prototype.dequeue = function () {
+ this.joinObservers.forEach(function (v) { v.queue.shift(); });
+ };
+
+ ActivePlan.prototype.match = function () {
+ var i, len, hasValues = true;
+ for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
+ if (this.joinObserverArray[i].queue.length === 0) {
+ hasValues = false;
+ break;
+ }
+ }
+ if (hasValues) {
+ var firstValues = [],
+ isCompleted = false;
+ for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
+ firstValues.push(this.joinObserverArray[i].queue[0]);
+ this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
+ }
+ if (isCompleted) {
+ this.onCompleted();
+ } else {
+ this.dequeue();
+ var values = [];
+ for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
+ values.push(firstValues[i].value);
+ }
+ this.onNext.apply(this, values);
+ }
+ }
+ };
+
+ var JoinObserver = (function (__super__) {
+ inherits(JoinObserver, __super__);
+
+ 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;
+
+ JoinObserverPrototype.next = function (notification) {
+ if (!this.isDisposed) {
+ if (notification.kind === 'E') {
+ return this.onError(notification.exception);
+ }
+ this.queue.push(notification);
+ var activePlans = this.activePlans.slice(0);
+ for (var i = 0, len = activePlans.length; i < len; i++) {
+ activePlans[i].match();
+ }
+ }
+ };
+
+ JoinObserverPrototype.error = noop;
+ JoinObserverPrototype.completed = noop;
+
+ JoinObserverPrototype.addActivePlan = function (activePlan) {
+ this.activePlans.push(activePlan);
+ };
+
+ JoinObserverPrototype.subscribe = function () {
+ this.subscription.setDisposable(this.source.materialize().subscribe(this));
+ };
+
+ JoinObserverPrototype.removeActivePlan = function (activePlan) {
+ this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
+ this.activePlans.length === 0 && this.dispose();
+ };
+
+ 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 {Function} 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 len = arguments.length, plans;
+ if (Array.isArray(arguments[0])) {
+ plans = arguments[0];
+ } else {
+ plans = new Array(len);
+ for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
+ }
+ return new AnonymousObservable(function (o) {
+ var activePlans = [],
+ externalSubscriptions = new Map();
+ var outObserver = observerCreate(
+ function (x) { o.onNext(x); },
+ function (err) {
+ externalSubscriptions.forEach(function (v) { v.onError(err); });
+ o.onError(err);
+ },
+ function (x) { o.onCompleted(); }
+ );
+ try {
+ for (var 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);
+ activePlans.length === 0 && o.onCompleted();
+ }));
+ }
+ } catch (e) {
+ observableThrow(e).subscribe(o);
+ }
+ var group = new CompositeDisposable();
+ externalSubscriptions.forEach(function (joinObserver) {
+ joinObserver.subscribe();
+ group.add(joinObserver);
+ });
+
+ return group;
+ });
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 34 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ observableNever = Observable.never,
+ isEqual = Rx.internals.isEqual,
+ defaultSubComparer = Rx.helpers.defaultSubComparer;
+
+ /**
+ * jortSort checks if your inputs are sorted. Note that this is only for a sequence with an end.
+ * See http://jort.technology/ for full details.
+ * @returns {Observable} An observable which has a single value of true if sorted, else false.
+ */
+ observableProto.jortSort = function () {
+ return this.jortSortUntil(observableNever());
+ };
+
+ /**
+ * jortSort checks if your inputs are sorted until another Observable sequence fires.
+ * See http://jort.technology/ for full details.
+ * @returns {Observable} An observable which has a single value of true if sorted, else false.
+ */
+ observableProto.jortSortUntil = function (other) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var arr = [];
+ return source.takeUntil(other).subscribe(
+ arr.push.bind(arr),
+ observer.onError.bind(observer),
+ function () {
+ var sorted = arr.slice(0).sort(defaultSubComparer);
+ observer.onNext(isEqual(arr, sorted));
+ observer.onCompleted();
+ });
+ }, source);
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 35 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // Aliases
+ var Scheduler = Rx.Scheduler,
+ PriorityQueue = Rx.internals.PriorityQueue,
+ ScheduledItem = Rx.internals.ScheduledItem,
+ SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive,
+ disposableEmpty = Rx.Disposable.empty,
+ inherits = Rx.internals.inherits,
+ defaultSubComparer = Rx.helpers.defaultSubComparer,
+ notImplemented = Rx.helpers.notImplemented;
+
+ /** Provides a set of extension methods for virtual time scheduling. */
+ Rx.VirtualTimeScheduler = (function (__super__) {
+
+ 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 ArgumentOutOfRangeError(); }
+ 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 ArgumentOutOfRangeError(); }
+ 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 ArgumentOutOfRangeError(); }
+
+ 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));
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 36 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [!(function webpackMissingModule() { var e = new Error("Cannot find module \"rx.virtualtime\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()), exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ root.Rx = factory(root, exports, Rx);
+ return root.Rx;
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // Defaults
+ var Observer = Rx.Observer,
+ Observable = Rx.Observable,
+ Notification = Rx.Notification,
+ VirtualTimeScheduler = Rx.VirtualTimeScheduler,
+ Disposable = Rx.Disposable,
+ disposableEmpty = Disposable.empty,
+ disposableCreate = Disposable.create,
+ CompositeDisposable = Rx.CompositeDisposable,
+ SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
+ inherits = Rx.internals.inherits,
+ defaultComparer = Rx.internals.isEqual;
+
+ function OnNextPredicate(predicate) {
+ this.predicate = predicate;
+ };
+
+ OnNextPredicate.prototype.equals = function (other) {
+ if (other === this) { return true; }
+ if (other == null) { return false; }
+ if (other.kind !== 'N') { return false; }
+ return this.predicate(other.value);
+ };
+
+ function OnErrorPredicate(predicate) {
+ this.predicate = predicate;
+ };
+
+ OnErrorPredicate.prototype.equals = function (other) {
+ if (other === this) { return true; }
+ if (other == null) { return false; }
+ if (other.kind !== 'E') { return false; }
+ return this.predicate(other.exception);
+ };
+
+ var ReactiveTest = Rx.ReactiveTest = {
+ /** Default virtual time used for creation of observable sequences in unit tests. */
+ created: 100,
+ /** Default virtual time used to subscribe to observable sequences in unit tests. */
+ subscribed: 200,
+ /** Default virtual time used to dispose subscriptions in unit tests. */
+ disposed: 1000,
+
+ /**
+ * Factory method for an OnNext notification record at a given time with a given value or a predicate function.
+ *
+ * 1 - ReactiveTest.onNext(200, 42);
+ * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; });
+ *
+ * @param ticks Recorded virtual time the OnNext notification occurs.
+ * @param value Recorded value stored in the OnNext notification or a predicate.
+ * @return Recorded OnNext notification.
+ */
+ onNext: function (ticks, value) {
+ return typeof value === 'function' ?
+ new Recorded(ticks, new OnNextPredicate(value)) :
+ new Recorded(ticks, Notification.createOnNext(value));
+ },
+ /**
+ * Factory method for an OnError notification record at a given time with a given error.
+ *
+ * 1 - ReactiveTest.onNext(200, new Error('error'));
+ * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; });
+ *
+ * @param ticks Recorded virtual time the OnError notification occurs.
+ * @param exception Recorded exception stored in the OnError notification.
+ * @return Recorded OnError notification.
+ */
+ onError: function (ticks, error) {
+ return typeof error === 'function' ?
+ new Recorded(ticks, new OnErrorPredicate(error)) :
+ new Recorded(ticks, Notification.createOnError(error));
+ },
+ /**
+ * Factory method for an OnCompleted notification record at a given time.
+ *
+ * @param ticks Recorded virtual time the OnCompleted notification occurs.
+ * @return Recorded OnCompleted notification.
+ */
+ onCompleted: function (ticks) {
+ return new Recorded(ticks, Notification.createOnCompleted());
+ },
+ /**
+ * Factory method for a subscription record based on a given subscription and disposal time.
+ *
+ * @param start Virtual time indicating when the subscription was created.
+ * @param end Virtual time indicating when the subscription was disposed.
+ * @return Subscription object.
+ */
+ subscribe: function (start, end) {
+ return new Subscription(start, end);
+ }
+ };
+
+ /**
+ * Creates a new object recording the production of the specified value at the given virtual time.
+ *
+ * @constructor
+ * @param {Number} time Virtual time the value was produced on.
+ * @param {Mixed} value Value that was produced.
+ * @param {Function} comparer An optional comparer.
+ */
+ var Recorded = Rx.Recorded = function (time, value, comparer) {
+ this.time = time;
+ this.value = value;
+ this.comparer = comparer || defaultComparer;
+ };
+
+ /**
+ * Checks whether the given recorded object is equal to the current instance.
+ *
+ * @param {Recorded} other Recorded object to check for equality.
+ * @returns {Boolean} true if both objects are equal; false otherwise.
+ */
+ Recorded.prototype.equals = function (other) {
+ return this.time === other.time && this.comparer(this.value, other.value);
+ };
+
+ /**
+ * Returns a string representation of the current Recorded value.
+ *
+ * @returns {String} String representation of the current Recorded value.
+ */
+ Recorded.prototype.toString = function () {
+ return this.value.toString() + '@' + this.time;
+ };
+
+ /**
+ * Creates a new subscription object with the given virtual subscription and unsubscription time.
+ *
+ * @constructor
+ * @param {Number} subscribe Virtual time at which the subscription occurred.
+ * @param {Number} unsubscribe Virtual time at which the unsubscription occurred.
+ */
+ var Subscription = Rx.Subscription = function (start, end) {
+ this.subscribe = start;
+ this.unsubscribe = end || Number.MAX_VALUE;
+ };
+
+ /**
+ * Checks whether the given subscription is equal to the current instance.
+ * @param other Subscription object to check for equality.
+ * @returns {Boolean} true if both objects are equal; false otherwise.
+ */
+ Subscription.prototype.equals = function (other) {
+ return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe;
+ };
+
+ /**
+ * Returns a string representation of the current Subscription value.
+ * @returns {String} String representation of the current Subscription value.
+ */
+ Subscription.prototype.toString = function () {
+ return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')';
+ };
+
+ var MockDisposable = Rx.MockDisposable = function (scheduler) {
+ this.scheduler = scheduler;
+ this.disposes = [];
+ this.disposes.push(this.scheduler.clock);
+ };
+
+ MockDisposable.prototype.dispose = function () {
+ this.disposes.push(this.scheduler.clock);
+ };
+
+ var MockObserver = (function (__super__) {
+ inherits(MockObserver, __super__);
+
+ function MockObserver(scheduler) {
+ __super__.call(this);
+ this.scheduler = scheduler;
+ this.messages = [];
+ }
+
+ var MockObserverPrototype = MockObserver.prototype;
+
+ MockObserverPrototype.onNext = function (value) {
+ this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value)));
+ };
+
+ MockObserverPrototype.onError = function (exception) {
+ this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception)));
+ };
+
+ MockObserverPrototype.onCompleted = function () {
+ this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted()));
+ };
+
+ return MockObserver;
+ })(Observer);
+
+ function MockPromise(scheduler, messages) {
+ var self = this;
+ this.scheduler = scheduler;
+ this.messages = messages;
+ this.subscriptions = [];
+ this.observers = [];
+ for (var i = 0, len = this.messages.length; i < len; i++) {
+ var message = this.messages[i],
+ notification = message.value;
+ (function (innerNotification) {
+ scheduler.scheduleAbsoluteWithState(null, message.time, function () {
+ var obs = self.observers.slice(0);
+
+ for (var j = 0, jLen = obs.length; j < jLen; j++) {
+ innerNotification.accept(obs[j]);
+ }
+ return disposableEmpty;
+ });
+ })(notification);
+ }
+ }
+
+ MockPromise.prototype.then = function (onResolved, onRejected) {
+ var self = this;
+
+ this.subscriptions.push(new Subscription(this.scheduler.clock));
+ var index = this.subscriptions.length - 1;
+
+ var newPromise;
+
+ var observer = Rx.Observer.create(
+ function (x) {
+ var retValue = onResolved(x);
+ if (retValue && typeof retValue.then === 'function') {
+ newPromise = retValue;
+ } else {
+ var ticks = self.scheduler.clock;
+ newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]);
+ }
+ var idx = self.observers.indexOf(observer);
+ self.observers.splice(idx, 1);
+ self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
+ },
+ function (err) {
+ onRejected(err);
+ var idx = self.observers.indexOf(observer);
+ self.observers.splice(idx, 1);
+ self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
+ }
+ );
+ this.observers.push(observer);
+
+ return newPromise || new MockPromise(this.scheduler, this.messages);
+ };
+
+ var HotObservable = (function (__super__) {
+
+ function subscribe(observer) {
+ var observable = this;
+ this.observers.push(observer);
+ this.subscriptions.push(new Subscription(this.scheduler.clock));
+ var index = this.subscriptions.length - 1;
+ return disposableCreate(function () {
+ var idx = observable.observers.indexOf(observer);
+ observable.observers.splice(idx, 1);
+ observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
+ });
+ }
+
+ inherits(HotObservable, __super__);
+
+ function HotObservable(scheduler, messages) {
+ __super__.call(this, subscribe);
+ var message, notification, observable = this;
+ this.scheduler = scheduler;
+ this.messages = messages;
+ this.subscriptions = [];
+ this.observers = [];
+ for (var i = 0, len = this.messages.length; i < len; i++) {
+ message = this.messages[i];
+ notification = message.value;
+ (function (innerNotification) {
+ scheduler.scheduleAbsoluteWithState(null, message.time, function () {
+ var obs = observable.observers.slice(0);
+
+ for (var j = 0, jLen = obs.length; j < jLen; j++) {
+ innerNotification.accept(obs[j]);
+ }
+ return disposableEmpty;
+ });
+ })(notification);
+ }
+ }
+
+ return HotObservable;
+ })(Observable);
+
+ var ColdObservable = (function (__super__) {
+
+ function subscribe(observer) {
+ var message, notification, observable = this;
+ this.subscriptions.push(new Subscription(this.scheduler.clock));
+ var index = this.subscriptions.length - 1;
+ var d = new CompositeDisposable();
+ for (var i = 0, len = this.messages.length; i < len; i++) {
+ message = this.messages[i];
+ notification = message.value;
+ (function (innerNotification) {
+ d.add(observable.scheduler.scheduleRelativeWithState(null, message.time, function () {
+ innerNotification.accept(observer);
+ return disposableEmpty;
+ }));
+ })(notification);
+ }
+ return disposableCreate(function () {
+ observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
+ d.dispose();
+ });
+ }
+
+ inherits(ColdObservable, __super__);
+
+ function ColdObservable(scheduler, messages) {
+ __super__.call(this, subscribe);
+ this.scheduler = scheduler;
+ this.messages = messages;
+ this.subscriptions = [];
+ }
+
+ return ColdObservable;
+ })(Observable);
+
+ /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */
+ Rx.TestScheduler = (function (__super__) {
+ inherits(TestScheduler, __super__);
+
+ function baseComparer(x, y) {
+ return x > y ? 1 : (x < y ? -1 : 0);
+ }
+
+ function TestScheduler() {
+ __super__.call(this, 0, baseComparer);
+ }
+
+ /**
+ * Schedules an action to be executed at the specified virtual time.
+ *
+ * @param state State passed to the action to be executed.
+ * @param dueTime Absolute virtual time at which to execute the action.
+ * @param action Action to be executed.
+ * @return Disposable object used to cancel the scheduled action (best effort).
+ */
+ TestScheduler.prototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
+ dueTime <= this.clock && (dueTime = this.clock + 1);
+ return __super__.prototype.scheduleAbsoluteWithState.call(this, state, dueTime, action);
+ };
+ /**
+ * Adds a relative virtual time to an absolute virtual time value.
+ *
+ * @param absolute Absolute virtual time value.
+ * @param relative Relative virtual time value to add.
+ * @return Resulting absolute virtual time sum value.
+ */
+ TestScheduler.prototype.add = function (absolute, relative) {
+ return absolute + relative;
+ };
+ /**
+ * Converts the absolute virtual time value to a DateTimeOffset value.
+ *
+ * @param absolute Absolute virtual time value to convert.
+ * @return Corresponding DateTimeOffset value.
+ */
+ TestScheduler.prototype.toDateTimeOffset = function (absolute) {
+ return new Date(absolute).getTime();
+ };
+ /**
+ * Converts the TimeSpan value to a relative virtual time value.
+ *
+ * @param timeSpan TimeSpan value to convert.
+ * @return Corresponding relative virtual time value.
+ */
+ TestScheduler.prototype.toRelative = function (timeSpan) {
+ return timeSpan;
+ };
+ /**
+ * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription.
+ *
+ * @param create Factory method to create an observable sequence.
+ * @param created Virtual time at which to invoke the factory to create an observable sequence.
+ * @param subscribed Virtual time at which to subscribe to the created observable sequence.
+ * @param disposed Virtual time at which to dispose the subscription.
+ * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
+ */
+ TestScheduler.prototype.startWithTiming = function (create, created, subscribed, disposed) {
+ var observer = this.createObserver(), source, subscription;
+
+ this.scheduleAbsoluteWithState(null, created, function () {
+ source = create();
+ return disposableEmpty;
+ });
+
+ this.scheduleAbsoluteWithState(null, subscribed, function () {
+ subscription = source.subscribe(observer);
+ return disposableEmpty;
+ });
+
+ this.scheduleAbsoluteWithState(null, disposed, function () {
+ subscription.dispose();
+ return disposableEmpty;
+ });
+
+ this.start();
+
+ return observer;
+ };
+
+ /**
+ * Starts the test scheduler and uses the specified virtual time to dispose the subscription to the sequence obtained through the factory function.
+ * Default virtual times are used for factory invocation and sequence subscription.
+ *
+ * @param create Factory method to create an observable sequence.
+ * @param disposed Virtual time at which to dispose the subscription.
+ * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
+ */
+ TestScheduler.prototype.startWithDispose = function (create, disposed) {
+ return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, disposed);
+ };
+
+ /**
+ * Starts the test scheduler and uses default virtual times to invoke the factory function, to subscribe to the resulting sequence, and to dispose the subscription.
+ *
+ * @param create Factory method to create an observable sequence.
+ * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
+ */
+ TestScheduler.prototype.startWithCreate = function (create) {
+ return this.startWithTiming(create, ReactiveTest.created, ReactiveTest.subscribed, ReactiveTest.disposed);
+ };
+
+ /**
+ * Creates a hot observable using the specified timestamped notification messages either as an array or arguments.
+ * @param messages Notifications to surface through the created sequence at their specified absolute virtual times.
+ * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications.
+ */
+ TestScheduler.prototype.createHotObservable = function () {
+ var len = arguments.length, args;
+ if (Array.isArray(arguments[0])) {
+ args = arguments[0];
+ } else {
+ args = new Array(len);
+ for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ }
+ return new HotObservable(this, args);
+ };
+
+ /**
+ * Creates a cold observable using the specified timestamped notification messages either as an array or arguments.
+ * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time.
+ * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications.
+ */
+ TestScheduler.prototype.createColdObservable = function () {
+ var len = arguments.length, args;
+ if (Array.isArray(arguments[0])) {
+ args = arguments[0];
+ } else {
+ args = new Array(len);
+ for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
+ }
+ return new ColdObservable(this, args);
+ };
+
+ /**
+ * Creates a resolved promise with the given value and ticks
+ * @param {Number} ticks The absolute time of the resolution.
+ * @param {Any} value The value to yield at the given tick.
+ * @returns {MockPromise} A mock Promise which fulfills with the given value.
+ */
+ TestScheduler.prototype.createResolvedPromise = function (ticks, value) {
+ return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]);
+ };
+
+ /**
+ * Creates a rejected promise with the given reason and ticks
+ * @param {Number} ticks The absolute time of the resolution.
+ * @param {Any} reason The reason for rejection to yield at the given tick.
+ * @returns {MockPromise} A mock Promise which rejects with the given reason.
+ */
+ TestScheduler.prototype.createRejectedPromise = function (ticks, reason) {
+ return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]);
+ };
+
+ /**
+ * Creates an observer that records received notification messages and timestamps those.
+ * @return Observer that can be used to assert the timing of received notifications.
+ */
+ TestScheduler.prototype.createObserver = function () {
+ return new MockObserver(this);
+ };
+
+ return TestScheduler;
+ })(VirtualTimeScheduler);
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 37 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
+
+ ;(function (factory) {
+ 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;
+ }
+
+ // Because of build optimizers
+ if (true) {
+ !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) {
+ return factory(root, exports, Rx);
+ }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+ } else if (typeof module === 'object' && module && module.exports === freeExports) {
+ module.exports = factory(root, module.exports, require('./rx'));
+ } else {
+ root.Rx = factory(root, {}, root.Rx);
+ }
+ }.call(this, function (root, exp, Rx, undefined) {
+
+ // Refernces
+ var Observable = Rx.Observable,
+ observableProto = Observable.prototype,
+ AnonymousObservable = Rx.AnonymousObservable,
+ observableDefer = Observable.defer,
+ observableEmpty = Observable.empty,
+ observableNever = Observable.never,
+ observableThrow = Observable.throwException,
+ observableFromArray = Observable.fromArray,
+ timeoutScheduler = Rx.Scheduler['default'],
+ SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
+ SerialDisposable = Rx.SerialDisposable,
+ CompositeDisposable = Rx.CompositeDisposable,
+ RefCountDisposable = Rx.RefCountDisposable,
+ Subject = Rx.Subject,
+ addRef = Rx.internals.addRef,
+ normalizeTime = Rx.Scheduler.normalize,
+ helpers = Rx.helpers,
+ isPromise = helpers.isPromise,
+ isFunction = helpers.isFunction,
+ isScheduler = Rx.Scheduler.isScheduler,
+ observableFromPromise = Observable.fromPromise;
+
+ var errorObj = {e: {}};
+ var tryCatchTarget;
+ function tryCatcher() {
+ try {
+ return tryCatchTarget.apply(this, arguments);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+ }
+ function tryCatch(fn) {
+ if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
+ tryCatchTarget = fn;
+ return tryCatcher;
+ }
+ function thrower(e) {
+ throw e;
+ }
+
+ 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 d = dueTime, p = normalizeTime(period);
+ return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
+ if (p > 0) {
+ var now = scheduler.now();
+ d = d + p;
+ d <= now && (d = now + p);
+ }
+ observer.onNext(count);
+ self(count + 1, d);
+ });
+ });
+ }
+
+ function observableTimerTimeSpan(dueTime, scheduler) {
+ return new AnonymousObservable(function (observer) {
+ return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
+ observer.onNext(0);
+ observer.onCompleted();
+ });
+ });
+ }
+
+ function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
+ return dueTime === period ?
+ new AnonymousObservable(function (observer) {
+ return scheduler.schedulePeriodicWithState(0, period, function (count) {
+ observer.onNext(count);
+ return count + 1;
+ });
+ }) :
+ observableDefer(function () {
+ return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
+ });
+ }
+
+ /**
+ * Returns an observable sequence that produces a value after each period.
+ *
+ * @example
+ * 1 - res = Rx.Observable.interval(1000);
+ * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
+ *
+ * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
+ * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
+ * @returns {Observable} An observable sequence that produces a value after each period.
+ */
+ var observableinterval = Observable.interval = function (period, scheduler) {
+ return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
+ };
+
+ /**
+ * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
+ * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
+ * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
+ * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
+ * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
+ */
+ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
+ var period;
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+ if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
+ period = periodOrScheduler;
+ } else if (isScheduler(periodOrScheduler)) {
+ scheduler = periodOrScheduler;
+ }
+ if (dueTime instanceof Date && period === undefined) {
+ return observableTimerDate(dueTime.getTime(), scheduler);
+ }
+ if (dueTime instanceof Date && period !== undefined) {
+ period = periodOrScheduler;
+ return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
+ }
+ return period === undefined ?
+ observableTimerTimeSpan(dueTime, scheduler) :
+ observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
+ };
+
+ function observableDelayTimeSpan(source, dueTime, scheduler) {
+ return new AnonymousObservable(function (observer) {
+ var active = false,
+ cancelable = new SerialDisposable(),
+ exception = null,
+ q = [],
+ running = false,
+ subscription;
+ subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
+ var d, shouldRun;
+ if (notification.value.kind === 'E') {
+ q = [];
+ q.push(notification);
+ exception = notification.value.exception;
+ shouldRun = !running;
+ } else {
+ q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
+ shouldRun = !active;
+ active = true;
+ }
+ if (shouldRun) {
+ if (exception !== null) {
+ observer.onError(exception);
+ } else {
+ d = new SingleAssignmentDisposable();
+ cancelable.setDisposable(d);
+ d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
+ var e, recurseDueTime, result, shouldRecurse;
+ if (exception !== null) {
+ return;
+ }
+ running = true;
+ do {
+ result = null;
+ if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
+ result = q.shift().value;
+ }
+ if (result !== null) {
+ result.accept(observer);
+ }
+ } while (result !== null);
+ shouldRecurse = false;
+ recurseDueTime = 0;
+ if (q.length > 0) {
+ shouldRecurse = true;
+ recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
+ } else {
+ active = false;
+ }
+ e = exception;
+ running = false;
+ if (e !== null) {
+ observer.onError(e);
+ } else if (shouldRecurse) {
+ self(recurseDueTime);
+ }
+ }));
+ }
+ }
+ });
+ return new CompositeDisposable(subscription, cancelable);
+ }, source);
+ }
+
+ 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.
+ * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
+ * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
+ * @returns {Observable} The debounced sequence.
+ */
+ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
+ var subscription = source.subscribe(
+ function (x) {
+ hasvalue = true;
+ value = x;
+ id++;
+ var currentId = id,
+ d = new SingleAssignmentDisposable();
+ cancelable.setDisposable(d);
+ d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
+ hasvalue && id === currentId && observer.onNext(value);
+ hasvalue = false;
+ }));
+ },
+ function (e) {
+ cancelable.dispose();
+ observer.onError(e);
+ hasvalue = false;
+ id++;
+ },
+ function () {
+ cancelable.dispose();
+ hasvalue && observer.onNext(value);
+ observer.onCompleted();
+ hasvalue = false;
+ id++;
+ });
+ return new CompositeDisposable(subscription, cancelable);
+ }, this);
+ };
+
+ /**
+ * @deprecated use #debounce or #throttleWithTimeout instead.
+ */
+ observableProto.throttle = function(dueTime, scheduler) {
+ //deprecate('throttle', 'debounce or throttleWithTimeout');
+ return this.debounce(dueTime, scheduler);
+ };
+
+ /**
+ * Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
+ * @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 (isScheduler(timeShiftOrScheduler)) {
+ 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);
+
+ 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;
+ if (isSpan) {
+ nextSpan += timeShift;
+ }
+ if (isShift) {
+ nextShift += timeShift;
+ }
+ m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
+ if (isShift) {
+ var s = new Subject();
+ q.push(s);
+ observer.onNext(addRef(s, refCountDisposable));
+ }
+ isSpan && q.shift().onCompleted();
+ createTimer();
+ }));
+ };
+ q.push(new Subject());
+ observer.onNext(addRef(q[0], refCountDisposable));
+ createTimer();
+ groupDisposable.add(source.subscribe(
+ function (x) {
+ for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
+ },
+ function (e) {
+ for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
+ observer.onError(e);
+ },
+ function () {
+ for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
+ observer.onCompleted();
+ }
+ ));
+ return refCountDisposable;
+ }, source);
+ };
+
+ /**
+ * 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.
+ * @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 timerD = new SerialDisposable(),
+ groupDisposable = new CompositeDisposable(timerD),
+ refCountDisposable = new RefCountDisposable(groupDisposable),
+ n = 0,
+ windowId = 0,
+ s = new Subject();
+
+ function createTimer(id) {
+ var m = new SingleAssignmentDisposable();
+ timerD.setDisposable(m);
+ m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
+ if (id !== windowId) { return; }
+ n = 0;
+ var newId = ++windowId;
+ s.onCompleted();
+ s = new Subject();
+ observer.onNext(addRef(s, refCountDisposable));
+ createTimer(newId);
+ }));
+ }
+
+ observer.onNext(addRef(s, refCountDisposable));
+ createTimer(0);
+
+ groupDisposable.add(source.subscribe(
+ function (x) {
+ var newId = 0, newWindow = false;
+ s.onNext(x);
+ 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;
+ }, source);
+ };
+
+ /**
+ * 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.default);
+ *
+ * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default 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 (o) {
+ var atEnd = false, value, hasValue = false;
+
+ function sampleSubscribe() {
+ if (hasValue) {
+ hasValue = false;
+ o.onNext(value);
+ }
+ atEnd && o.onCompleted();
+ }
+
+ var sourceSubscription = new SingleAssignmentDisposable();
+ sourceSubscription.setDisposable(source.subscribe(
+ function (newValue) {
+ hasValue = true;
+ value = newValue;
+ },
+ function (e) { o.onError(e); },
+ function () {
+ atEnd = true;
+ sourceSubscription.dispose();
+ }
+ ));
+
+ return new CompositeDisposable(
+ sourceSubscription,
+ sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe)
+ );
+ }, source);
+ }
+
+ /**
+ * 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 = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+ return typeof intervalOrSampler === 'number' ?
+ sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
+ sampleObservable(this, intervalOrSampler);
+ };
+
+ /**
+ * Returns the source observable sequence or the other observable sequence if dueTime elapses.
+ * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
+ * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
+ * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
+ * @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
+ */
+ observableProto.timeout = function (dueTime, other, scheduler) {
+ (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+
+ var source = this, schedulerMethod = dueTime instanceof Date ?
+ 'scheduleWithAbsolute' :
+ 'scheduleWithRelative';
+
+ return new AnonymousObservable(function (observer) {
+ var id = 0,
+ original = new SingleAssignmentDisposable(),
+ subscription = new SerialDisposable(),
+ switched = false,
+ timer = new SerialDisposable();
+
+ subscription.setDisposable(original);
+
+ function createTimer() {
+ var myId = id;
+ timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
+ if (id === myId) {
+ isPromise(other) && (other = observableFromPromise(other));
+ subscription.setDisposable(other.subscribe(observer));
+ }
+ }));
+ }
+
+ createTimer();
+
+ original.setDisposable(source.subscribe(function (x) {
+ if (!switched) {
+ id++;
+ observer.onNext(x);
+ createTimer();
+ }
+ }, function (e) {
+ if (!switched) {
+ id++;
+ observer.onError(e);
+ }
+ }, function () {
+ if (!switched) {
+ id++;
+ observer.onCompleted();
+ }
+ }));
+ return new CompositeDisposable(subscription, timer);
+ }, source);
+ };
+
+ /**
+ * 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;
+ return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) {
+ hasResult && observer.onNext(state);
+
+ try {
+ if (first) {
+ first = false;
+ } else {
+ state = iterate(state);
+ }
+ hasResult = condition(state);
+ if (hasResult) {
+ var result = resultSelector(state);
+ var time = timeSelector(state);
+ }
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ if (hasResult) {
+ self(result, 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;
+ return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) {
+ hasResult && observer.onNext(state);
+
+ try {
+ if (first) {
+ first = false;
+ } else {
+ state = iterate(state);
+ }
+ hasResult = condition(state);
+ if (hasResult) {
+ var result = resultSelector(state);
+ var time = timeSelector(state);
+ }
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+ if (hasResult) {
+ self(result, time);
+ } else {
+ observer.onCompleted();
+ }
+ });
+ });
+ };
+
+ /**
+ * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
+ *
+ * @example
+ * 1 - res = source.delaySubscription(5000); // 5s
+ * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
+ *
+ * @param {Number} dueTime Relative or absolute time shift of the subscription.
+ * @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) {
+ var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative';
+ var source = this;
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+ return new AnonymousObservable(function (o) {
+ var d = new SerialDisposable();
+
+ d.setDisposable(scheduler[scheduleMethod](dueTime, function() {
+ d.setDisposable(source.subscribe(o));
+ }));
+
+ return d;
+ }, this);
+ };
+
+ /**
+ * 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 (isFunction(subscriptionDelay)) {
+ selector = subscriptionDelay;
+ } else {
+ subDelay = subscriptionDelay;
+ selector = delayDurationSelector;
+ }
+ return new AnonymousObservable(function (observer) {
+ var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
+
+ function start() {
+ subscription.setDisposable(source.subscribe(
+ function (x) {
+ var delay = tryCatch(selector)(x);
+ if (delay === errorObj) { return observer.onError(delay.e); }
+ var d = new SingleAssignmentDisposable();
+ delays.add(d);
+ d.setDisposable(delay.subscribe(
+ function () {
+ observer.onNext(x);
+ delays.remove(d);
+ done();
+ },
+ function (e) { observer.onError(e); },
+ function () {
+ observer.onNext(x);
+ delays.remove(d);
+ done();
+ }
+ ))
+ },
+ function (e) { observer.onError(e); },
+ function () {
+ atEnd = true;
+ subscription.dispose();
+ done();
+ }
+ ))
+ }
+
+ function done () {
+ atEnd && delays.length === 0 && observer.onCompleted();
+ }
+
+ if (!subDelay) {
+ start();
+ } else {
+ subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start));
+ }
+
+ return new CompositeDisposable(subscription, delays);
+ }, this);
+ };
+
+ /**
+ * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
+ * @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;
+ 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;
+
+ function setTimer(timeout) {
+ var myId = id;
+
+ function timerWins () {
+ return id === myId;
+ }
+
+ var d = new SingleAssignmentDisposable();
+ timer.setDisposable(d);
+ d.setDisposable(timeout.subscribe(function () {
+ timerWins() && subscription.setDisposable(other.subscribe(observer));
+ d.dispose();
+ }, function (e) {
+ timerWins() && observer.onError(e);
+ }, function () {
+ timerWins() && subscription.setDisposable(other.subscribe(observer));
+ }));
+ };
+
+ setTimer(firstTimeout);
+
+ function observerWins() {
+ 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(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
+ }
+ }, function (e) {
+ observerWins() && observer.onError(e);
+ }, function () {
+ observerWins() && observer.onCompleted();
+ }));
+ return new CompositeDisposable(subscription, timer);
+ }, source);
+ };
+
+ /**
+ * Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
+ * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
+ * @returns {Observable} The debounced sequence.
+ */
+ observableProto.debounceWithSelector = function (durationSelector) {
+ var source = this;
+ return new AnonymousObservable(function (observer) {
+ var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
+ var subscription = source.subscribe(function (x) {
+ var throttle;
+ try {
+ throttle = durationSelector(x);
+ } catch (e) {
+ observer.onError(e);
+ return;
+ }
+
+ isPromise(throttle) && (throttle = observableFromPromise(throttle));
+
+ hasValue = true;
+ value = x;
+ id++;
+ var currentid = id, d = new SingleAssignmentDisposable();
+ cancelable.setDisposable(d);
+ d.setDisposable(throttle.subscribe(function () {
+ hasValue && id === currentid && observer.onNext(value);
+ hasValue = false;
+ d.dispose();
+ }, observer.onError.bind(observer), function () {
+ hasValue && id === currentid && observer.onNext(value);
+ hasValue = false;
+ d.dispose();
+ }));
+ }, function (e) {
+ cancelable.dispose();
+ observer.onError(e);
+ hasValue = false;
+ id++;
+ }, function () {
+ cancelable.dispose();
+ hasValue && observer.onNext(value);
+ observer.onCompleted();
+ hasValue = false;
+ id++;
+ });
+ return new CompositeDisposable(subscription, cancelable);
+ }, source);
+ };
+
+ /**
+ * @deprecated use #debounceWithSelector instead.
+ */
+ observableProto.throttleWithSelector = function (durationSelector) {
+ //deprecate('throttleWithSelector', 'debounceWithSelector');
+ return this.debounceWithSelector(durationSelector);
+ };
+
+ /**
+ * 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 (o) {
+ 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) {
+ o.onNext(q.shift().value);
+ }
+ }, function (e) { o.onError(e); }, function () {
+ var now = scheduler.now();
+ while (q.length > 0 && now - q[0].interval >= duration) {
+ o.onNext(q.shift().value);
+ }
+ o.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * 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.
+ * @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 (o) {
+ 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();
+ }
+ }, function (e) { o.onError(e); }, function () {
+ var now = scheduler.now();
+ while (q.length > 0) {
+ var next = q.shift();
+ if (now - next.interval <= duration) { o.onNext(next.value); }
+ }
+ o.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * 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.
+ * @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 (o) {
+ 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();
+ }
+ }, function (e) { o.onError(e); }, function () {
+ var now = scheduler.now(), res = [];
+ while (q.length > 0) {
+ var next = q.shift();
+ now - next.interval <= duration && res.push(next.value);
+ }
+ o.onNext(res);
+ o.onCompleted();
+ });
+ }, source);
+ };
+
+ /**
+ * 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 (o) {
+ return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
+ }, source);
+ };
+
+ /**
+ * 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)));
+ }, source);
+ };
+
+ /**
+ * 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(), [scheduler]);
+ * 2 - res = source.skipUntilWithTime(5000, [scheduler]);
+ * @param {Date|Number} 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] 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 (o) {
+ var open = false;
+
+ return new CompositeDisposable(
+ scheduler[schedulerMethod](startTime, function () { open = true; }),
+ source.subscribe(
+ function (x) { open && o.onNext(x); },
+ function (e) { o.onError(e); }, function () { o.onCompleted(); }));
+ }, source);
+ };
+
+ /**
+ * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
+ * @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 (o) {
+ return new CompositeDisposable(
+ scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
+ source.subscribe(o));
+ }, source);
+ };
+
+ /**
+ * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
+ * @param {Number} windowDuration time to wait before emitting another item after emitting the last item
+ * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
+ * @returns {Observable} An Observable that performs the throttle operation.
+ */
+ observableProto.throttleFirst = function (windowDuration, scheduler) {
+ isScheduler(scheduler) || (scheduler = timeoutScheduler);
+ var duration = +windowDuration || 0;
+ if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
+ var source = this;
+ return new AnonymousObservable(function (o) {
+ var lastOnNext = 0;
+ return source.subscribe(
+ function (x) {
+ var now = scheduler.now();
+ if (lastOnNext === 0 || now - lastOnNext >= duration) {
+ lastOnNext = now;
+ o.onNext(x);
+ }
+ },function (e) { o.onError(e); }, function () { o.onCompleted(); }
+ );
+ }, source);
+ };
+
+ return Rx;
+ }));
+
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module)))
+
+/***/ },
+/* 38 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule invariant
+ */
+
+ 'use strict';
+
+ /**
+ * Use invariant() to assert state which your program assumes to be true.
+ *
+ * Provide sprintf-style format (only %s is supported) and arguments
+ * to provide information about what broke and what you were
+ * expecting.
+ *
+ * The invariant message will be stripped in production, but the invariant
+ * will remain to ensure logic does not differ in production.
+ */
+
+ var __DEV__ = process.env.NODE_ENV !== 'production';
+
+ var invariant = function(condition, format, a, b, c, d, e, f) {
+ if (__DEV__) {
+ if (format === undefined) {
+ throw new Error('invariant requires an error message argument');
+ }
+ }
+
+ if (!condition) {
+ var error;
+ if (format === undefined) {
+ 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];
+ var argIndex = 0;
+ error = new Error(
+ 'Invariant Violation: ' +
+ format.replace(/%s/g, function() { return args[argIndex++]; })
+ );
+ }
+
+ error.framesToPop = 1; // we don't care about invariant's own frame
+ throw error;
+ }
+ };
+
+ module.exports = invariant;
+
+
+/***/ },
+/* 39 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ // modified from https://github.com/es-shims/es6-shim
+ var keys = __webpack_require__(40);
+ var canBeObject = function (obj) {
+ return typeof obj !== 'undefined' && obj !== null;
+ };
+ var hasSymbols = __webpack_require__(42)();
+ var defineProperties = __webpack_require__(43);
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+ var isEnumerableOn = function (obj) {
+ return function isEnumerable(prop) {
+ return propIsEnumerable.call(obj, prop);
+ };
+ };
+
+ var assignShim = function assign(target, source1) {
+ if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
+ var objTarget = Object(target);
+ var s, source, i, props;
+ for (s = 1; s < arguments.length; ++s) {
+ source = Object(arguments[s]);
+ props = keys(source);
+ if (hasSymbols && Object.getOwnPropertySymbols) {
+ props.push.apply(props, Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source)));
+ }
+ for (i = 0; i < props.length; ++i) {
+ objTarget[props[i]] = source[props[i]];
+ }
+ }
+ return objTarget;
+ };
+
+ defineProperties(assignShim, {
+ shim: function shimObjectAssign() {
+ var assignHasPendingExceptions = function () {
+ if (!Object.assign || !Object.preventExtensions) {
+ return false;
+ }
+ // Firefox 37 still has "pending exception" logic in its Object.assign implementation,
+ // which is 72% slower than our shim, and Firefox 40's native implementation.
+ var thrower = Object.preventExtensions({ 1: 2 });
+ try {
+ Object.assign(thrower, 'xy');
+ } catch (e) {
+ return thrower[1] === 'y';
+ }
+ };
+ defineProperties(
+ Object,
+ { assign: assignShim },
+ { assign: assignHasPendingExceptions }
+ );
+ return Object.assign || assignShim;
+ }
+ });
+
+ module.exports = assignShim;
+
+
+
+/***/ },
+/* 40 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ // modified from https://github.com/es-shims/es5-shim
+ var has = Object.prototype.hasOwnProperty;
+ var toStr = Object.prototype.toString;
+ var slice = Array.prototype.slice;
+ var isArgs = __webpack_require__(41);
+ var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
+ var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
+ var dontEnums = [
+ 'toString',
+ 'toLocaleString',
+ 'valueOf',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'constructor'
+ ];
+
+ var keysShim = function keys(object) {
+ var isObject = object !== null && typeof object === 'object';
+ var isFunction = toStr.call(object) === '[object Function]';
+ var isArguments = isArgs(object);
+ var isString = isObject && toStr.call(object) === '[object String]';
+ var theKeys = [];
+
+ if (!isObject && !isFunction && !isArguments) {
+ throw new TypeError('Object.keys called on a non-object');
+ }
+
+ var skipProto = hasProtoEnumBug && isFunction;
+ if (isString && object.length > 0 && !has.call(object, 0)) {
+ for (var i = 0; i < object.length; ++i) {
+ theKeys.push(String(i));
+ }
+ }
+
+ if (isArguments && object.length > 0) {
+ for (var j = 0; j < object.length; ++j) {
+ theKeys.push(String(j));
+ }
+ } else {
+ for (var name in object) {
+ if (!(skipProto && name === 'prototype') && has.call(object, name)) {
+ theKeys.push(String(name));
+ }
+ }
+ }
+
+ if (hasDontEnumBug) {
+ var ctor = object.constructor;
+ var skipConstructor = ctor && ctor.prototype === object;
+
+ for (var k = 0; k < dontEnums.length; ++k) {
+ if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
+ theKeys.push(dontEnums[k]);
+ }
+ }
+ }
+ return theKeys;
+ };
+
+ keysShim.shim = function shimObjectKeys() {
+ if (!Object.keys) {
+ Object.keys = keysShim;
+ } else {
+ var keysWorksWithArguments = (function () {
+ // Safari 5.0 bug
+ return (Object.keys(arguments) || '').length === 2;
+ }(1, 2));
+ if (!keysWorksWithArguments) {
+ var originalKeys = Object.keys;
+ Object.keys = function keys(object) {
+ if (isArgs(object)) {
+ return originalKeys(slice.call(object));
+ } else {
+ return originalKeys(object);
+ }
+ };
+ }
+ }
+ return Object.keys || keysShim;
+ };
+
+ module.exports = keysShim;
+
+
+/***/ },
+/* 41 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ var toStr = Object.prototype.toString;
+
+ module.exports = function isArguments(value) {
+ var str = toStr.call(value);
+ var isArgs = str === '[object Arguments]';
+ if (!isArgs) {
+ isArgs = str !== '[object Array]' &&
+ value !== null &&
+ typeof value === 'object' &&
+ typeof value.length === 'number' &&
+ value.length >= 0 &&
+ toStr.call(value.callee) === '[object Function]';
+ }
+ return isArgs;
+ };
+
+
+/***/ },
+/* 42 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var keys = __webpack_require__(40);
+
+ module.exports = function hasSymbols() {
+ if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
+ if (typeof Symbol.iterator === 'symbol') { return true; }
+
+ var obj = {};
+ var sym = Symbol('test');
+ if (typeof sym === 'string') { return false; }
+ obj[sym] = 42;
+ for (sym in obj) { return false; }
+ if (keys(obj).length !== 0) { return false; }
+ if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
+
+ if (typeof Object.getOwnPropertyNames === 'function') {
+ var names = Object.getOwnPropertyNames(obj);
+ if (names.length !== 0) { return false; }
+ }
+
+ var syms = Object.getOwnPropertySymbols(obj);
+ if (syms.length !== 1 || syms[0] !== sym) { return false; }
+
+ if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
+
+ if (typeof Object.getOwnPropertyDescriptor === 'function') {
+ var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
+ if (descriptor.value !== 42 || descriptor.enumerable !== true) { return false; }
+ }
+
+ return true;
+ };
+
+
+/***/ },
+/* 43 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ var keys = __webpack_require__(40);
+ var foreach = __webpack_require__(44);
+
+ var toStr = Object.prototype.toString;
+
+ var isFunction = function (fn) {
+ return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
+ };
+
+ var arePropertyDescriptorsSupported = function () {
+ var obj = {};
+ try {
+ Object.defineProperty(obj, 'x', { value: obj });
+ return obj.x === obj;
+ } catch (e) { /* this is IE 8. */
+ return false;
+ }
+ };
+ var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
+
+ var defineProperty = function (object, name, value, predicate) {
+ if (name in object && (!isFunction(predicate) || !predicate())) {
+ return;
+ }
+ if (supportsDescriptors) {
+ Object.defineProperty(object, name, {
+ configurable: true,
+ enumerable: false,
+ writable: true,
+ value: value
+ });
+ } else {
+ object[name] = value;
+ }
+ };
+
+ var defineProperties = function (object, map) {
+ var predicates = arguments.length > 2 ? arguments[2] : {};
+ foreach(keys(map), function (name) {
+ defineProperty(object, name, map[name], predicates[name]);
+ });
+ };
+
+ defineProperties.supportsDescriptors = !!supportsDescriptors;
+
+ module.exports = defineProperties;
+
+
+/***/ },
+/* 44 */
+/***/ function(module, exports) {
+
+
+ var hasOwn = Object.prototype.hasOwnProperty;
+ var toString = Object.prototype.toString;
+
+ module.exports = function forEach (obj, fn, ctx) {
+ if (toString.call(fn) !== '[object Function]') {
+ throw new TypeError('iterator must be a function');
+ }
+ var l = obj.length;
+ if (l === +l) {
+ for (var i = 0; i < l; i++) {
+ fn.call(ctx, obj[i], i, obj);
+ }
+ } else {
+ for (var k in obj) {
+ if (hasOwn.call(obj, k)) {
+ fn.call(ctx, obj[k], k, obj);
+ }
+ }
+ }
+ };
+
+
+
+/***/ },
+/* 45 */
+/***/ function(module, exports, __webpack_require__) {
+
+ // # Wait For Utility
+ //
+ // Takes observables for arguments,
+ // converts them to hot observables
+ // then waits for each one to publish a value
+ //
+ // returns an observable.
+ //
+ // *Note:* it's good practice to use a firstOrDefault
+ // observable if you just want a short lived subscription
+ // and a timeout if you don't want to wait forever!
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+ exports['default'] = waitFor;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _utils = __webpack_require__(46);
+
+ var debug = (0, _debug2['default'])('thundercats:waitFor');
+ var slice = Array.prototype.slice;
+
+ function waitFor(observables) {
+ return _rx2['default'].Observable.from(arguments).tapOnNext(function (observable) {
+ return (0, _utils.isObservable)(observable) ? true : new Error('waitFor only take observables but got %s', observable);
+ }).map(function (observable) {
+ return observable.publish();
+ }).tapOnNext(function (observable) {
+ return observable.connect();
+ }).toArray().tap(function () {
+ return debug('starting waitFor');
+ }).flatMap(function (arrayOfObservables) {
+ return _rx2['default'].Observable.combineLatest(arrayOfObservables, function () {
+ return slice.call(arguments);
+ });
+ }).doOnNext(function () {
+ return debug('waitFor onNext!');
+ });
+ }
+
+ module.exports = exports['default'];
+
+/***/ },
+/* 46 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _invariant = __webpack_require__(38);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ exports['default'] = {
+ areObservable: areObservable,
+ createObjectValidator: createObjectValidator,
+ getName: getName,
+ getNameOrNull: getNameOrNull,
+ isObservable: isObservable,
+ isPromise: isPromise
+ };
+
+ var __DEV__ = process.env.NODE_ENV !== 'production';
+
+ function areObservable(observables) {
+ return Array.isArray(observables) && observables.length > 0 && observables.reduce(function (bool, observable) {
+ return bool && isObservable(observable);
+ }, true);
+ }
+
+ function createObjectValidator(message) {
+ return function (obj) {
+ /* istanbul ignore else */
+ if (__DEV__) {
+ (0, _invariant2['default'])(obj && typeof obj === 'object', message, obj);
+ }
+ };
+ }
+
+ function getName(comp) {
+ return '' + (getNameOrNull(comp) || 'Anonymous');
+ }
+
+ function getNameOrNull(comp) {
+ return comp && comp.displayName || comp.constructor && comp.constructor.displayName || null;
+ }
+
+ function isObservable(observable) {
+ return observable && typeof observable.subscribe === 'function';
+ }
+
+ function isPromise(promise) {
+ return promise && typeof promise.then === 'function';
+ }
+ module.exports = exports['default'];
+
+/***/ },
+/* 47 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _invariant = __webpack_require__(38);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var _warning = __webpack_require__(48);
+
+ var _warning2 = _interopRequireDefault(_warning);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _Store = __webpack_require__(49);
+
+ var _Store2 = _interopRequireDefault(_Store);
+
+ var _Actions = __webpack_require__(23);
+
+ var _Actions2 = _interopRequireDefault(_Actions);
+
+ var _Translate = __webpack_require__(51);
+
+ var _Translate2 = _interopRequireDefault(_Translate);
+
+ var _Render = __webpack_require__(52);
+
+ var _Render2 = _interopRequireDefault(_Render);
+
+ var _utils = __webpack_require__(46);
+
+ var debug = (0, _debug2['default'])('thundercats:cat');
+
+ var Register = {
+ store: function store(stores, Store, args) {
+ var name = (0, _utils.getName)(Store);
+ if (stores.has(name.toLowerCase())) {
+ return (0, _warning2['default'])(false, 'Attempted to add a Store class, %s, that already exists in the Cat', name);
+ }
+ var store = new (Function.prototype.bind.apply(Store, args))();
+ debug('registering store %s', name);
+ stores.set(name.toLowerCase(), store);
+ return store;
+ },
+
+ actions: function actions(actionsMap, Actions, args) {
+ var name = (0, _utils.getName)(Actions);
+ if (actionsMap.has(name.toLowerCase())) {
+ return (0, _warning2['default'])(false, 'Attempted to add an Actions class, %s, that already exists in the Cat', name);
+ }
+ var _actions = new (Function.prototype.bind.apply(Actions, args))();
+ debug('registering actions %s', name);
+ actionsMap.set(name.toLowerCase(), _actions);
+ return _actions;
+ }
+ };
+
+ exports.Register = Register;
+
+ var Cat = (function () {
+ function Cat() {
+ _classCallCheck(this, Cat);
+
+ this.stores = new Map();
+ this.actions = new Map();
+ }
+
+ _createClass(Cat, [{
+ key: 'register',
+ value: function register(StoreOrActions) {
+ (0, _invariant2['default'])(_Store2['default'].isPrototypeOf(StoreOrActions) || _Actions2['default'].isPrototypeOf(StoreOrActions), 'Attempted to add a class that is not a ThunderCats Store or Action');
+
+ var name = (0, _utils.getNameOrNull)(StoreOrActions);
+
+ (0, _invariant2['default'])(typeof name === 'string', 'Attempted to add a Store/Actions that does not have a displayName');
+
+ var isStore = _Store2['default'].isPrototypeOf(StoreOrActions);
+ var args = [].slice.call(arguments);
+
+ return isStore ? Register.store(this.stores, StoreOrActions, args) : Register.actions(this.actions, StoreOrActions, args);
+ }
+ }, {
+ key: 'getStore',
+ value: function getStore(store) {
+ return this.stores.get(('' + store).toLowerCase());
+ }
+ }, {
+ key: 'getActions',
+ value: function getActions(action) {
+ return this.actions.get(('' + action).toLowerCase());
+ }
+ }, {
+ key: 'dehydrate',
+ value: function dehydrate() {
+ return _Translate2['default'].dehydrate(_rx2['default'].Observable.from(this.stores.values()));
+ }
+ }, {
+ key: 'hydrate',
+ value: function hydrate(catState) {
+ return _Translate2['default'].hydrate(_rx2['default'].Observable.from(this.stores.values()), _rx2['default'].Observable.just(catState));
+ }
+ }, {
+ key: 'serialize',
+ value: function serialize() {
+ return _Translate2['default'].serialize(_rx2['default'].Observable.from(this.stores.values()));
+ }
+ }, {
+ key: 'deserialize',
+ value: function deserialize(stringyCatState) {
+ return _Translate2['default'].deserialize(_rx2['default'].Observable.from(this.stores.values()), _rx2['default'].Observable.just(stringyCatState));
+ }
+ }, {
+ key: 'render',
+ value: function render(Component, DOMContainer) {
+ return _Render2['default'].render(this, Component, DOMContainer);
+ }
+ }, {
+ key: 'renderToString',
+ value: function renderToString(Component) {
+ return _Render2['default'].renderToString(this, Component);
+ }
+ }]);
+
+ return Cat;
+ })();
+
+ exports['default'] = Cat;
+
+/***/ },
+/* 48 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ */
+
+ 'use strict';
+
+ /**
+ * Similar to invariant but only logs a warning if the condition is not met.
+ * This can be used to log issues in development environments in critical
+ * paths. Removing the logging code for production environments will keep the
+ * same logic and follow the same code paths.
+ */
+
+ var __DEV__ = process.env.NODE_ENV !== 'production';
+
+ var warning = function() {};
+
+ if (__DEV__) {
+ warning = function(condition, format, args) {
+ var len = arguments.length;
+ args = new Array(len > 2 ? len - 2 : 0);
+ for (var key = 2; key < len; key++) {
+ args[key - 2] = arguments[key];
+ }
+ if (format === undefined) {
+ throw new Error(
+ '`warning(condition, format, ...args)` requires a warning ' +
+ 'message argument'
+ );
+ }
+
+ if (format.length < 10 || (/^[s\W]*$/).test(format)) {
+ throw new Error(
+ 'The warning format should be able to uniquely identify this ' +
+ 'warning. Please, use a more descriptive format than: ' + format
+ );
+ }
+
+ if (!condition) {
+ var argIndex = 0;
+ var message = 'Warning: ' +
+ format.replace(/%s/g, function() {
+ return args[argIndex++];
+ });
+ if (typeof console !== 'undefined') {
+ console.error(message);
+ }
+ try {
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ throw new Error(message);
+ } catch(x) {}
+ }
+ };
+ }
+
+ module.exports = warning;
+
+
+/***/ },
+/* 49 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
+
+ var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
+
+ exports.applyOperation = applyOperation;
+ exports.notifyObservers = notifyObservers;
+ exports.dispose = dispose;
+ exports.checkId = checkId;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
+
+ function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _nodeUuid = __webpack_require__(50);
+
+ var _nodeUuid2 = _interopRequireDefault(_nodeUuid);
+
+ var _invariant = __webpack_require__(38);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _objectAssign = __webpack_require__(39);
+
+ var _objectAssign2 = _interopRequireDefault(_objectAssign);
+
+ var _Actions = __webpack_require__(23);
+
+ var _Actions2 = _interopRequireDefault(_Actions);
+
+ var _utils = __webpack_require__(46);
+
+ var debug = (0, _debug2['default'])('thundercats:store');
+ var __DEV__ = process.env.NODE_ENV !== 'production';
+
+ function validateObservable(observable) {
+ /* istanbul ignore else */
+ if (__DEV__) {
+ (0, _invariant2['default'])((0, _utils.isObservable)(observable), 'register should get observables but was given %s', observable);
+ }
+ return observable;
+ }
+
+ function addOperation(observable, validateItem, map) {
+ return validateObservable(observable).tap(validateItem).map(map);
+ }
+
+ var Register = {
+ observable: function observable(obs, actionsArr, storeName) {
+ actionsArr = actionsArr.slice();
+ (0, _invariant2['default'])((0, _utils.isObservable)(obs), '%s should register observables but was given %s', storeName, obs);
+
+ debug('%s registering action', storeName);
+
+ actionsArr.push(obs);
+ return actionsArr;
+ },
+
+ actions: function actions(actionsInst, actionsArr, storeName) {
+ var actionNames = (0, _Actions.getActionNames)(actionsInst);
+
+ debug('%s register actions class %s', storeName, (0, _utils.getName)(actionsInst));
+
+ return actionNames.reduce(function (actionsArr, name) {
+ return Register.observable(actionsInst[name], actionsArr, storeName);
+ }, actionsArr);
+ }
+ };
+
+ exports.Register = Register;
+ var Optimism = {
+ confirm: function confirm(uid, history) {
+ checkId(uid, history);
+ history.get(uid).confirmed = true;
+ history.forEach(function (operation, uid) {
+ /* istanbul ignore else */
+ if (operation.confirmed) {
+ history['delete'](uid);
+ }
+ });
+ return history;
+ },
+ revert: function revert(uid, history) {
+ checkId(uid, history);
+ // initial value
+ var value = history.get(uid).oldValue;
+ var found = false;
+ history.forEach(function (descriptor, _uid) {
+ if (uid === _uid) {
+ found = true;
+ return;
+ }
+ if (!found) {
+ return;
+ }
+ descriptor.oldValue = value;
+ value = applyOperation(value, descriptor.operation);
+ });
+
+ history['delete'](uid);
+ return {
+ history: history,
+ value: value
+ };
+ }
+ };
+
+ exports.Optimism = Optimism;
+
+ function applyOperation(oldValue, operation) {
+ var replace = operation.replace;
+ var transform = operation.transform;
+ var set = operation.set;
+
+ if (replace) {
+ return replace;
+ } else if (transform) {
+ return transform(oldValue);
+ } else if (set) {
+ return (0, _objectAssign2['default'])({}, oldValue, set);
+ } else {
+ return oldValue;
+ }
+ }
+
+ function notifyObservers(value, observers) {
+ debug('starting notify cycle');
+ observers.forEach(function (observer, uid) {
+ debug('notifying %s', uid);
+ observer.onNext(value);
+ });
+ }
+
+ function dispose(subscription, history) {
+ if (subscription) {
+ subscription.dispose();
+ }
+ return new Map();
+ }
+
+ function checkId(id, history) {
+ (0, _invariant2['default'])(history.has(id), 'an unknown operation id was used that is not within its history.' + 'it may have been called outside of context');
+ }
+
+ var Store = (function (_Rx$Observable) {
+ function Store() {
+ _classCallCheck(this, Store);
+
+ _get(Object.getPrototypeOf(Store.prototype), 'constructor', this).call(this, Store.prototype._subscribe);
+
+ this.value = {};
+ this._operationsSubscription = null;
+ this.actions = [];
+ this.observers = new Map();
+ this.history = new Map();
+ }
+
+ _inherits(Store, _Rx$Observable);
+
+ _createClass(Store, [{
+ key: 'register',
+ value: function register(observableOrActionsInstance) {
+ if (observableOrActionsInstance instanceof _Actions2['default']) {
+ this.actions = Register.actions(observableOrActionsInstance, this.actions, (0, _utils.getName)(this));
+ return this.actions;
+ }
+ this.actions = Register.observable(observableOrActionsInstance, this.actions, (0, _utils.getName)(this));
+ return this.actions;
+ }
+ }, {
+ key: 'hasObservers',
+ value: function hasObservers() {
+ return !!this.observers.size;
+ }
+ }, {
+ key: '_init',
+ value: function _init() {
+ debug('initiating %s', (0, _utils.getName)(this));
+ this.history = dispose(this._operationsSubscription, this.history);
+
+ (0, _invariant2['default'])(this.actions.length, '%s must have at least one action to listen to but has %s', (0, _utils.getName)(this), this.actions.length);
+
+ var operations = [];
+ this.actions.forEach(function (observable) {
+ operations.push(observable);
+ });
+
+ (0, _invariant2['default'])((0, _utils.areObservable)(operations), '"%s" actions should be an array of observables', (0, _utils.getName)(this));
+
+ this._operationsSubscription = _rx2['default'].Observable.merge(operations).filter(function (operation) {
+ return typeof operation.replace === 'object' ? !!operation.replace : true;
+ }).filter(function (operation) {
+ return typeof operation.set === 'object' ? !!operation.set : true;
+ }).doOnNext(function (operation) {
+ (0, _invariant2['default'])(typeof operation === 'object', 'invalid operation, operations should be an object, given : %s', operation);
+
+ (0, _invariant2['default'])(typeof operation.replace === 'object' || typeof operation.transform === 'function' || typeof operation.set === 'object', 'invalid operation, ' + 'operations should have a replace(an object), ' + 'transform(a function), or set(an object) property but got %s', Object.keys(operation));
+
+ if ('optimistic' in operation) {
+ (0, _invariant2['default'])((0, _utils.isPromise)(operation.optimistic) || (0, _utils.isObservable)(operation.optimistic), 'invalid operation, optimistic should be a promise or observable,' + 'given : %s', operation.optimistic);
+ }
+ }).subscribe(this._opsOnNext.bind(this), this.opsOnError.bind(this), this.opsOnCompleted.bind(this));
+ }
+ }, {
+ key: '_opsOnNext',
+ value: function _opsOnNext(operation) {
+ var _this = this;
+
+ var ops = (0, _objectAssign2['default'])({}, operation);
+
+ debug('on next called');
+ var oldValue = this.value;
+ this.value = applyOperation(this.value, ops);
+ notifyObservers(this.value, this.observers);
+
+ var uid = _nodeUuid2['default'].v1();
+
+ this.history.set(uid, {
+ operation: ops,
+ oldValue: oldValue
+ });
+
+ if ('optimistic' in ops) {
+ var optimisticObs = (0, _utils.isPromise)(ops.optimistic) ? _rx2['default'].Observable.fromPromise(ops.optimistic) : ops.optimistic;
+
+ optimisticObs.firstOrDefault().subscribe(function () {}, function (err) {
+ debug('optimistic error. reverting changes', err);
+
+ var _Optimism$revert = Optimism.revert(uid, _this.history);
+
+ var value = _Optimism$revert.value;
+ var history = _Optimism$revert.history;
+
+ _this.history = history;
+ _this.value = value;
+ notifyObservers(value, _this.observers);
+ }, function () {
+ return _this.history = Optimism.confirm(uid, _this.history);
+ });
+ } else {
+ Optimism.confirm(uid, this.history);
+ }
+ }
+ }, {
+ key: 'opsOnError',
+ value: function opsOnError(err) {
+ throw new Error('An error has occurred in the operations observer: ' + err);
+ }
+ }, {
+ key: 'opsOnCompleted',
+ value: function opsOnCompleted() {
+ console.warn('operations observable has terminated without error');
+ }
+ }, {
+ key: '_subscribe',
+ value: function _subscribe(observer) {
+ var _this2 = this;
+
+ var uid = _nodeUuid2['default'].v1();
+
+ /* istanbul ignore else */
+ if (!this.hasObservers()) {
+ this._init();
+ }
+
+ debug('adding observer %s', uid);
+ this.observers.set(uid, observer);
+
+ observer.onNext(this.value);
+
+ return _rx2['default'].Disposable.create(function () {
+ debug('Disposing obserable %s', uid);
+ _this2.observers['delete'](uid);
+ /* istanbul ignore else */
+ if (!_this2.hasObservers()) {
+ debug('All observers disposed, disposing operations observer');
+ _this2.history = dispose(_this2._operationsSubscription, _this2.history);
+ }
+ });
+ }
+ }, {
+ key: 'serialize',
+ value: function serialize() {
+ return this.value ? JSON.stringify(this.value) : '';
+ }
+ }, {
+ key: 'deserialize',
+ value: function deserialize(stringyData) {
+ var data = JSON.parse(stringyData);
+ (0, _invariant2['default'])(data && typeof data === 'object', '%s deserialize must return an object but got: %s', (0, _utils.getName)(this), data);
+ this.value = data;
+ return this.value;
+ }
+ }], [{
+ key: 'createRegistrar',
+ value: function createRegistrar(store) {
+ function register(observable) {
+ store.actions = Register.observable(observable, store.actions, (0, _utils.getName)(store));
+ return store.actions;
+ }
+ return register;
+ }
+ }, {
+ key: 'fromMany',
+ value: function fromMany() {
+ return _rx2['default'].Observable.from(arguments).tap(validateObservable).toArray().flatMap(function (observables) {
+ return _rx2['default'].Observable.merge(observables);
+ });
+ }
+ }, {
+ key: 'replacer',
+ value: function replacer(observable) {
+ return addOperation(observable, (0, _utils.createObjectValidator)('setter should receive objects but was given %s'), function (replace) {
+ return { replace: replace };
+ });
+ }
+ }, {
+ key: 'setter',
+ value: function setter(observable) {
+ return addOperation(observable, (0, _utils.createObjectValidator)('setter should receive objects but was given %s'), function (set) {
+ return { set: set };
+ });
+ }
+ }, {
+ key: 'transformer',
+ value: function transformer(observable) {
+ return addOperation(observable, function (fun) {
+ /* istanbul ignore else */
+ if (__DEV__) {
+ (0, _invariant2['default'])(typeof fun === 'function', 'transform should receive functions but was given %s', fun);
+ }
+ }, function (transform) {
+ return { transform: transform };
+ });
+ }
+ }]);
+
+ return Store;
+ })(_rx2['default'].Observable);
+
+ exports['default'] = Store;
+
+/***/ },
+/* 50 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var __WEBPACK_AMD_DEFINE_RESULT__;// uuid.js
+ //
+ // Copyright (c) 2010-2012 Robert Kieffer
+ // MIT License - http://opensource.org/licenses/mit-license.php
+
+ (function() {
+ var _global = this;
+
+ // Unique ID creation requires a high quality random # generator. We feature
+ // detect to determine the best RNG source, normalizing to a function that
+ // returns 128-bits of randomness, since that's what's usually required
+ var _rng;
+
+ // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
+ //
+ // Moderately fast, high quality
+ if (typeof(_global.require) == 'function') {
+ try {
+ var _rb = _global.require('crypto').randomBytes;
+ _rng = _rb && function() {return _rb(16);};
+ } catch(e) {}
+ }
+
+ if (!_rng && _global.crypto && crypto.getRandomValues) {
+ // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
+ //
+ // Moderately fast, high quality
+ var _rnds8 = new Uint8Array(16);
+ _rng = function whatwgRNG() {
+ crypto.getRandomValues(_rnds8);
+ return _rnds8;
+ };
+ }
+
+ if (!_rng) {
+ // Math.random()-based (RNG)
+ //
+ // If all else fails, use Math.random(). It's fast, but is of unspecified
+ // quality.
+ var _rnds = new Array(16);
+ _rng = function() {
+ for (var i = 0, r; i < 16; i++) {
+ if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
+ _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
+ }
+
+ return _rnds;
+ };
+ }
+
+ // Buffer class to use
+ var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array;
+
+ // Maps for number <-> hex string conversion
+ var _byteToHex = [];
+ var _hexToByte = {};
+ for (var i = 0; i < 256; i++) {
+ _byteToHex[i] = (i + 0x100).toString(16).substr(1);
+ _hexToByte[_byteToHex[i]] = i;
+ }
+
+ // **`parse()` - Parse a UUID into it's component bytes**
+ function parse(s, buf, offset) {
+ var i = (buf && offset) || 0, ii = 0;
+
+ buf = buf || [];
+ s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
+ if (ii < 16) { // Don't overflow!
+ buf[i + ii++] = _hexToByte[oct];
+ }
+ });
+
+ // Zero out remaining bytes if string was short
+ while (ii < 16) {
+ buf[i + ii++] = 0;
+ }
+
+ return buf;
+ }
+
+ // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
+ function unparse(buf, offset) {
+ var i = offset || 0, bth = _byteToHex;
+ return bth[buf[i++]] + bth[buf[i++]] +
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
+ bth[buf[i++]] + bth[buf[i++]] +
+ bth[buf[i++]] + bth[buf[i++]] +
+ bth[buf[i++]] + bth[buf[i++]];
+ }
+
+ // **`v1()` - Generate time-based UUID**
+ //
+ // Inspired by https://github.com/LiosK/UUID.js
+ // and http://docs.python.org/library/uuid.html
+
+ // random #'s we need to init node and clockseq
+ var _seedBytes = _rng();
+
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ var _nodeId = [
+ _seedBytes[0] | 0x01,
+ _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
+ ];
+
+ // Per 4.2.2, randomize (14 bit) clockseq
+ var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
+
+ // Previous uuid creation time
+ var _lastMSecs = 0, _lastNSecs = 0;
+
+ // See https://github.com/broofa/node-uuid for API details
+ function v1(options, buf, offset) {
+ var i = buf && offset || 0;
+ var b = buf || [];
+
+ options = options || {};
+
+ var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
+
+ // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+ var msecs = options.msecs != null ? options.msecs : new Date().getTime();
+
+ // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+ var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
+
+ // Time since last uuid creation (in msecs)
+ var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
+
+ // Per 4.2.1.2, Bump clockseq on clock regression
+ if (dt < 0 && options.clockseq == null) {
+ clockseq = clockseq + 1 & 0x3fff;
+ }
+
+ // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
+ nsecs = 0;
+ }
+
+ // Per 4.2.1.2 Throw error if too many uuids are requested
+ if (nsecs >= 10000) {
+ throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
+ }
+
+ _lastMSecs = msecs;
+ _lastNSecs = nsecs;
+ _clockseq = clockseq;
+
+ // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+ msecs += 12219292800000;
+
+ // `time_low`
+ var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff;
+
+ // `time_mid`
+ var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff;
+
+ // `time_high_and_version`
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+ b[i++] = tmh >>> 16 & 0xff;
+
+ // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+ b[i++] = clockseq >>> 8 | 0x80;
+
+ // `clock_seq_low`
+ b[i++] = clockseq & 0xff;
+
+ // `node`
+ var node = options.node || _nodeId;
+ for (var n = 0; n < 6; n++) {
+ b[i + n] = node[n];
+ }
+
+ return buf ? buf : unparse(b);
+ }
+
+ // **`v4()` - Generate random UUID**
+
+ // See https://github.com/broofa/node-uuid for API details
+ function v4(options, buf, offset) {
+ // Deprecated - 'format' argument, as supported in v1.2
+ var i = buf && offset || 0;
+
+ if (typeof(options) == 'string') {
+ buf = options == 'binary' ? new BufferClass(16) : null;
+ options = null;
+ }
+ options = options || {};
+
+ var rnds = options.random || (options.rng || _rng)();
+
+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
+
+ // Copy bytes to buffer, if provided
+ if (buf) {
+ for (var ii = 0; ii < 16; ii++) {
+ buf[i + ii] = rnds[ii];
+ }
+ }
+
+ return buf || unparse(rnds);
+ }
+
+ // Export public API
+ var uuid = v4;
+ uuid.v1 = v1;
+ uuid.v4 = v4;
+ uuid.parse = parse;
+ uuid.unparse = unparse;
+ uuid.BufferClass = BufferClass;
+
+ if (typeof(module) != 'undefined' && module.exports) {
+ // Publish as node.js module
+ module.exports = uuid;
+ } else if (true) {
+ // Publish as AMD module
+ !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {return uuid;}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
+
+
+ } else {
+ // Publish as global (in browsers)
+ var _previousRoot = _global.uuid;
+
+ // **`noConflict()` - (browser only) to reset global 'uuid' var**
+ uuid.noConflict = function() {
+ _global.uuid = _previousRoot;
+ return uuid;
+ };
+
+ _global.uuid = uuid;
+ }
+ }).call(this);
+
+
+/***/ },
+/* 51 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _objectAssign = __webpack_require__(39);
+
+ var _objectAssign2 = _interopRequireDefault(_objectAssign);
+
+ var _invariant = __webpack_require__(38);
+
+ var _invariant2 = _interopRequireDefault(_invariant);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _utils = __webpack_require__(46);
+
+ var debug = (0, _debug2['default'])('thundercats:translate');
+
+ exports['default'] = {
+ dehydrate: function dehydrate(storesObservable) {
+ return storesObservable
+ // store must have displayName and value
+ .filter(function (store) {
+ return !!(0, _utils.getNameOrNull)(store) && !!store.value;
+ }).map(function (store) {
+ return _defineProperty({}, (0, _utils.getName)(store), store.value);
+ }).reduce(function (allDats, storeDats) {
+ return (0, _objectAssign2['default'])(allDats, storeDats);
+ }, {}).map(function (allDats) {
+ return allDats;
+ }).tapOnError(function (err) {
+ debug('an error occurred while dehydrating stores', err);
+ });
+ },
+
+ hydrate: function hydrate(storesObservable, catStateObservable) {
+ return _rx2['default'].Observable.combineLatest([storesObservable, catStateObservable.tap((0, _utils.createObjectValidator)('hydrate should get objects but got %s'))], function (store, stateMap) {
+ return {
+ store: store,
+ data: stateMap[(0, _utils.getNameOrNull)(store)]
+ };
+ })
+ // filter out falsey data and non objects
+ .filter(function (_ref2) {
+ var data = _ref2.data;
+ return data && typeof data === 'object';
+ })
+ // assign value to store
+ .tap(function (_ref3) {
+ var store = _ref3.store;
+ var data = _ref3.data;
+
+ debug('updating %s with value: ', (0, _utils.getName)(store), data);
+ store.value = data;
+ })
+ // wait to run through all the stores
+ ['do'](null, function (err) {
+ return debug('deserialize encountered a err', err);
+ }, function () {
+ return debug('deserialize completed');
+ }).lastOrDefault().map(function () {
+ return true;
+ });
+ },
+
+ deserialize: function deserialize(storesObservable, stringyCatStateObservable) {
+ var catStateObservable = stringyCatStateObservable.tap(function (stringyCatState) {
+ (0, _invariant2['default'])(typeof stringyCatState === 'string', 'deserialize expects a string but got %s', stringyCatState);
+ }).map(function (stringyCatState) {
+ return JSON.parse(stringyCatState);
+ }).tap(function (catState) {
+ (0, _invariant2['default'])(typeof catState === 'object', 'parsed value of deserialize argument should be an object or ' + 'null but got %s', catState);
+ });
+
+ return this.hydrate(storesObservable, catStateObservable);
+ },
+
+ serialize: function serialize(storesObservable) {
+ return this.dehydrate(storesObservable).map(function (allDats) {
+ return JSON.stringify(allDats);
+ }).map(function (allDats) {
+ return typeof allDats === 'string' ? allDats : '{}';
+ }).tapOnError(function (err) {
+ debug('an error occurred while stringifing stores', err);
+ });
+ }
+ };
+ module.exports = exports['default'];
+
+/***/ },
+/* 52 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, '__esModule', {
+ value: true
+ });
+ exports.fetch = fetch;
+ exports.RenderToObs = RenderToObs;
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
+
+ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
+
+ var _rx = __webpack_require__(24);
+
+ var _rx2 = _interopRequireDefault(_rx);
+
+ var _react = __webpack_require__(53);
+
+ var _react2 = _interopRequireDefault(_react);
+
+ var _objectAssign = __webpack_require__(39);
+
+ var _objectAssign2 = _interopRequireDefault(_objectAssign);
+
+ var _debug = __webpack_require__(15);
+
+ var _debug2 = _interopRequireDefault(_debug);
+
+ var _ContextWrapper = __webpack_require__(208);
+
+ var _ContextWrapper2 = _interopRequireDefault(_ContextWrapper);
+
+ var _waitFor = __webpack_require__(45);
+
+ var _waitFor2 = _interopRequireDefault(_waitFor);
+
+ var _utils = __webpack_require__(46);
+
+ var debug = (0, _debug2['default'])('thundercats:render');
+
+ function fetch(fetchMap, stores) {
+ if (!fetchMap || fetchMap.size === 0) {
+ debug('cat found empty fetch map');
+ return _rx2['default'].Observable['return']({
+ data: {},
+ fetchMap: fetchMap
+ });
+ }
+
+ var fetchCtx = _rx2['default'].Observable.from(fetchMap.values()).shareReplay();
+
+ var waitForStores = fetchCtx.pluck('store')
+ // store should have names
+ .filter(function (store) {
+ return !!(0, _utils.getNameOrNull)(store);
+ }).toArray().tap(function (arrayOfStores) {
+ return debug('waiting for %s stores', arrayOfStores.length);
+ }).flatMap(function (arrayOfStores) {
+ return _waitFor2['default'].apply(undefined, _toConsumableArray(arrayOfStores)).firstOrDefault();
+ });
+
+ var storeNames = fetchCtx.pluck('store').map(function (store) {
+ return (0, _utils.getName)(store);
+ });
+
+ var fetchObs = fetchCtx.map(function (_ref2) {
+ var action = _ref2.action;
+ var payload = _ref2.payload;
+ return { action: action, payload: payload };
+ }).tapOnNext(function () {
+ return debug('init individual fetchers');
+ }).tapOnNext(function (_ref3) {
+ var action = _ref3.action;
+ var payload = _ref3.payload;
+
+ action(payload);
+ }).tapOnCompleted(function () {
+ return debug('fetchers activated');
+ }).toArray();
+
+ return _rx2['default'].Observable.combineLatest(waitForStores, fetchObs.delaySubscription(50), function (data) {
+ return data;
+ }).flatMap(function (data) {
+ return _rx2['default'].Observable.from(data);
+ }).zip(storeNames, function (data, name) {
+ return _defineProperty({}, name, data);
+ }).reduce(function (accu, item) {
+ return (0, _objectAssign2['default'])({}, accu, item);
+ }, {}).map(function (data) {
+ return { data: data, fetchMap: fetchMap };
+ });
+ }
+
+ function RenderToObs(Comp, DOMContainer) {
+ return new _rx2['default'].AnonymousObservable(function (observer) {
+ var instance = null;
+ instance = _react2['default'].render(Comp, DOMContainer, function (err) {
+ /* istanbul ignore else */
+ if (err) {
+ return observer.onError(err);
+ }
+ /* istanbul ignore else */
+ if (instance) {
+ observer.onNext(instance);
+ }
+ });
+ observer.onNext(instance);
+ });
+ }
+
+ exports['default'] = {
+ render: function render(cat, Component, DOMContainer) {
+ return _rx2['default'].Observable.just(Component).map(function (Comp) {
+ return _ContextWrapper2['default'].wrap(Comp, cat);
+ }).flatMap(function (Burrito) {
+ return RenderToObs(Burrito, DOMContainer);
+ }, function (Burrito, inst) {
+ return inst;
+ });
+ },
+
+ renderToString: function renderToString(cat, Component) {
+ var stores = cat.stores;
+
+ var fetchMap = new Map();
+ cat.fetchMap = fetchMap;
+ return _rx2['default'].Observable.just(Component).map(function (Comp) {
+ return _ContextWrapper2['default'].wrap(Comp, cat);
+ }).doOnNext(function (Burrito) {
+ debug('initiation fetcher registration');
+ _react2['default'].renderToStaticMarkup(Burrito);
+ debug('fetcher registration complete');
+ }).flatMap(function () {
+ return fetch(fetchMap, stores);
+ }, function (Burrito, _ref4) {
+ var data = _ref4.data;
+ var fetchMap = _ref4.fetchMap;
+
+ return {
+ Burrito: Burrito,
+ data: data,
+ fetchMap: fetchMap
+ };
+ }).map(function (_ref5) {
+ var Burrito = _ref5.Burrito;
+ var data = _ref5.data;
+ var fetchMap = _ref5.fetchMap;
+
+ var markup = _react2['default'].renderToString(Burrito);
+ return {
+ markup: markup,
+ data: data,
+ fetchMap: fetchMap
+ };
+ }).firstOrDefault().tapOnNext(function () {
+ return cat.fetchMap = null;
+ });
+ }
+ };
+
+/***/ },
+/* 53 */
+/***/ function(module, exports, __webpack_require__) {
+
+ module.exports = __webpack_require__(54);
+
+
+/***/ },
+/* 54 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule React
+ */
+
+ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
+
+ 'use strict';
+
+ var EventPluginUtils = __webpack_require__(55);
+ var ReactChildren = __webpack_require__(59);
+ var ReactComponent = __webpack_require__(73);
+ var ReactClass = __webpack_require__(88);
+ var ReactContext = __webpack_require__(63);
+ var ReactCurrentOwner = __webpack_require__(68);
+ var ReactElement = __webpack_require__(62);
+ var ReactElementValidator = __webpack_require__(81);
+ var ReactDOM = __webpack_require__(91);
+ var ReactDOMTextComponent = __webpack_require__(93);
+ var ReactDefaultInjection = __webpack_require__(142);
+ var ReactInstanceHandles = __webpack_require__(71);
+ var ReactMount = __webpack_require__(118);
+ var ReactPerf = __webpack_require__(77);
+ var ReactPropTypes = __webpack_require__(173);
+ var ReactReconciler = __webpack_require__(78);
+ var ReactServerRendering = __webpack_require__(205);
+
+ var assign = __webpack_require__(64);
+ var findDOMNode = __webpack_require__(162);
+ var onlyChild = __webpack_require__(207);
+
+ ReactDefaultInjection.inject();
+
+ var createElement = ReactElement.createElement;
+ var createFactory = ReactElement.createFactory;
+ var cloneElement = ReactElement.cloneElement;
+
+ if ("production" !== process.env.NODE_ENV) {
+ createElement = ReactElementValidator.createElement;
+ createFactory = ReactElementValidator.createFactory;
+ cloneElement = ReactElementValidator.cloneElement;
+ }
+
+ var render = ReactPerf.measure('React', 'render', ReactMount.render);
+
+ var React = {
+ Children: {
+ map: ReactChildren.map,
+ forEach: ReactChildren.forEach,
+ count: ReactChildren.count,
+ only: onlyChild
+ },
+ Component: ReactComponent,
+ DOM: ReactDOM,
+ PropTypes: ReactPropTypes,
+ initializeTouchEvents: function(shouldUseTouch) {
+ EventPluginUtils.useTouchEvents = shouldUseTouch;
+ },
+ createClass: ReactClass.createClass,
+ createElement: createElement,
+ cloneElement: cloneElement,
+ createFactory: createFactory,
+ createMixin: function(mixin) {
+ // Currently a noop. Will be used to validate and trace mixins.
+ return mixin;
+ },
+ constructAndRenderComponent: ReactMount.constructAndRenderComponent,
+ constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
+ findDOMNode: findDOMNode,
+ render: render,
+ renderToString: ReactServerRendering.renderToString,
+ renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
+ unmountComponentAtNode: ReactMount.unmountComponentAtNode,
+ isValidElement: ReactElement.isValidElement,
+ withContext: ReactContext.withContext,
+
+ // Hook for JSX spread, don't use this for anything else.
+ __spread: assign
+ };
+
+ // Inject the runtime into a devtools global hook regardless of browser.
+ // Allows for debugging when the hook is injected on the page.
+ if (
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
+ CurrentOwner: ReactCurrentOwner,
+ InstanceHandles: ReactInstanceHandles,
+ Mount: ReactMount,
+ Reconciler: ReactReconciler,
+ TextComponent: ReactDOMTextComponent
+ });
+ }
+
+ if ("production" !== process.env.NODE_ENV) {
+ var ExecutionEnvironment = __webpack_require__(102);
+ if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
+
+ // If we're in Chrome, look for the devtools marker and provide a download
+ // link if not installed.
+ if (navigator.userAgent.indexOf('Chrome') > -1) {
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
+ console.debug(
+ 'Download the React DevTools for a better development experience: ' +
+ 'https://fb.me/react-devtools'
+ );
+ }
+ }
+
+ var expectedFeatures = [
+ // shims
+ Array.isArray,
+ Array.prototype.every,
+ Array.prototype.forEach,
+ Array.prototype.indexOf,
+ Array.prototype.map,
+ Date.now,
+ Function.prototype.bind,
+ Object.keys,
+ String.prototype.split,
+ String.prototype.trim,
+
+ // shams
+ Object.create,
+ Object.freeze
+ ];
+
+ for (var i = 0; i < expectedFeatures.length; i++) {
+ if (!expectedFeatures[i]) {
+ console.error(
+ 'One or more ES5 shim/shams expected by React are not available: ' +
+ 'https://fb.me/react-warning-polyfills'
+ );
+ break;
+ }
+ }
+ }
+ }
+
+ React.version = '0.13.3';
+
+ module.exports = React;
+
+
+/***/ },
+/* 55 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule EventPluginUtils
+ */
+
+ 'use strict';
+
+ var EventConstants = __webpack_require__(56);
+
+ var invariant = __webpack_require__(58);
+
+ /**
+ * Injected dependencies:
+ */
+
+ /**
+ * - `Mount`: [required] Module that can convert between React dom IDs and
+ * actual node references.
+ */
+ var injection = {
+ Mount: null,
+ injectMount: function(InjectedMount) {
+ injection.Mount = InjectedMount;
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ InjectedMount && InjectedMount.getNode,
+ 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' +
+ 'is missing getNode.'
+ ) : invariant(InjectedMount && InjectedMount.getNode));
+ }
+ }
+ };
+
+ var topLevelTypes = EventConstants.topLevelTypes;
+
+ function isEndish(topLevelType) {
+ return topLevelType === topLevelTypes.topMouseUp ||
+ topLevelType === topLevelTypes.topTouchEnd ||
+ topLevelType === topLevelTypes.topTouchCancel;
+ }
+
+ function isMoveish(topLevelType) {
+ return topLevelType === topLevelTypes.topMouseMove ||
+ topLevelType === topLevelTypes.topTouchMove;
+ }
+ function isStartish(topLevelType) {
+ return topLevelType === topLevelTypes.topMouseDown ||
+ topLevelType === topLevelTypes.topTouchStart;
+ }
+
+
+ var validateEventDispatches;
+ if ("production" !== process.env.NODE_ENV) {
+ validateEventDispatches = function(event) {
+ var dispatchListeners = event._dispatchListeners;
+ var dispatchIDs = event._dispatchIDs;
+
+ var listenersIsArr = Array.isArray(dispatchListeners);
+ var idsIsArr = Array.isArray(dispatchIDs);
+ var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
+ var listenersLen = listenersIsArr ?
+ dispatchListeners.length :
+ dispatchListeners ? 1 : 0;
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ idsIsArr === listenersIsArr && IDsLen === listenersLen,
+ 'EventPluginUtils: Invalid `event`.'
+ ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen));
+ };
+ }
+
+ /**
+ * Invokes `cb(event, listener, id)`. Avoids using call if no scope is
+ * provided. The `(listener,id)` pair effectively forms the "dispatch" but are
+ * kept separate to conserve memory.
+ */
+ function forEachEventDispatch(event, cb) {
+ var dispatchListeners = event._dispatchListeners;
+ var dispatchIDs = event._dispatchIDs;
+ if ("production" !== process.env.NODE_ENV) {
+ validateEventDispatches(event);
+ }
+ if (Array.isArray(dispatchListeners)) {
+ for (var i = 0; i < dispatchListeners.length; i++) {
+ if (event.isPropagationStopped()) {
+ break;
+ }
+ // Listeners and IDs are two parallel arrays that are always in sync.
+ cb(event, dispatchListeners[i], dispatchIDs[i]);
+ }
+ } else if (dispatchListeners) {
+ cb(event, dispatchListeners, dispatchIDs);
+ }
+ }
+
+ /**
+ * Default implementation of PluginModule.executeDispatch().
+ * @param {SyntheticEvent} SyntheticEvent to handle
+ * @param {function} Application-level callback
+ * @param {string} domID DOM id to pass to the callback.
+ */
+ function executeDispatch(event, listener, domID) {
+ event.currentTarget = injection.Mount.getNode(domID);
+ var returnValue = listener(event, domID);
+ event.currentTarget = null;
+ return returnValue;
+ }
+
+ /**
+ * Standard/simple iteration through an event's collected dispatches.
+ */
+ function executeDispatchesInOrder(event, cb) {
+ forEachEventDispatch(event, cb);
+ event._dispatchListeners = null;
+ event._dispatchIDs = null;
+ }
+
+ /**
+ * Standard/simple iteration through an event's collected dispatches, but stops
+ * at the first dispatch execution returning true, and returns that id.
+ *
+ * @return id of the first dispatch execution who's listener returns true, or
+ * null if no listener returned true.
+ */
+ function executeDispatchesInOrderStopAtTrueImpl(event) {
+ var dispatchListeners = event._dispatchListeners;
+ var dispatchIDs = event._dispatchIDs;
+ if ("production" !== process.env.NODE_ENV) {
+ validateEventDispatches(event);
+ }
+ if (Array.isArray(dispatchListeners)) {
+ for (var i = 0; i < dispatchListeners.length; i++) {
+ if (event.isPropagationStopped()) {
+ break;
+ }
+ // Listeners and IDs are two parallel arrays that are always in sync.
+ if (dispatchListeners[i](event, dispatchIDs[i])) {
+ return dispatchIDs[i];
+ }
+ }
+ } else if (dispatchListeners) {
+ if (dispatchListeners(event, dispatchIDs)) {
+ return dispatchIDs;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @see executeDispatchesInOrderStopAtTrueImpl
+ */
+ function executeDispatchesInOrderStopAtTrue(event) {
+ var ret = executeDispatchesInOrderStopAtTrueImpl(event);
+ event._dispatchIDs = null;
+ event._dispatchListeners = null;
+ return ret;
+ }
+
+ /**
+ * Execution of a "direct" dispatch - there must be at most one dispatch
+ * accumulated on the event or it is considered an error. It doesn't really make
+ * sense for an event with multiple dispatches (bubbled) to keep track of the
+ * return values at each dispatch execution, but it does tend to make sense when
+ * dealing with "direct" dispatches.
+ *
+ * @return The return value of executing the single dispatch.
+ */
+ function executeDirectDispatch(event) {
+ if ("production" !== process.env.NODE_ENV) {
+ validateEventDispatches(event);
+ }
+ var dispatchListener = event._dispatchListeners;
+ var dispatchID = event._dispatchIDs;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !Array.isArray(dispatchListener),
+ 'executeDirectDispatch(...): Invalid `event`.'
+ ) : invariant(!Array.isArray(dispatchListener)));
+ var res = dispatchListener ?
+ dispatchListener(event, dispatchID) :
+ null;
+ event._dispatchListeners = null;
+ event._dispatchIDs = null;
+ return res;
+ }
+
+ /**
+ * @param {SyntheticEvent} event
+ * @return {bool} True iff number of dispatches accumulated is greater than 0.
+ */
+ function hasDispatches(event) {
+ return !!event._dispatchListeners;
+ }
+
+ /**
+ * General utilities that are useful in creating custom Event Plugins.
+ */
+ var EventPluginUtils = {
+ isEndish: isEndish,
+ isMoveish: isMoveish,
+ isStartish: isStartish,
+
+ executeDirectDispatch: executeDirectDispatch,
+ executeDispatch: executeDispatch,
+ executeDispatchesInOrder: executeDispatchesInOrder,
+ executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
+ hasDispatches: hasDispatches,
+ injection: injection,
+ useTouchEvents: false
+ };
+
+ module.exports = EventPluginUtils;
+
+
+/***/ },
+/* 56 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule EventConstants
+ */
+
+ 'use strict';
+
+ var keyMirror = __webpack_require__(57);
+
+ var PropagationPhases = keyMirror({bubbled: null, captured: null});
+
+ /**
+ * Types of raw signals from the browser caught at the top level.
+ */
+ var topLevelTypes = keyMirror({
+ topBlur: null,
+ topChange: null,
+ topClick: null,
+ topCompositionEnd: null,
+ topCompositionStart: null,
+ topCompositionUpdate: null,
+ topContextMenu: null,
+ topCopy: null,
+ topCut: null,
+ topDoubleClick: null,
+ topDrag: null,
+ topDragEnd: null,
+ topDragEnter: null,
+ topDragExit: null,
+ topDragLeave: null,
+ topDragOver: null,
+ topDragStart: null,
+ topDrop: null,
+ topError: null,
+ topFocus: null,
+ topInput: null,
+ topKeyDown: null,
+ topKeyPress: null,
+ topKeyUp: null,
+ topLoad: null,
+ topMouseDown: null,
+ topMouseMove: null,
+ topMouseOut: null,
+ topMouseOver: null,
+ topMouseUp: null,
+ topPaste: null,
+ topReset: null,
+ topScroll: null,
+ topSelectionChange: null,
+ topSubmit: null,
+ topTextInput: null,
+ topTouchCancel: null,
+ topTouchEnd: null,
+ topTouchMove: null,
+ topTouchStart: null,
+ topWheel: null
+ });
+
+ var EventConstants = {
+ topLevelTypes: topLevelTypes,
+ PropagationPhases: PropagationPhases
+ };
+
+ module.exports = EventConstants;
+
+
+/***/ },
+/* 57 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule keyMirror
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ var invariant = __webpack_require__(58);
+
+ /**
+ * Constructs an enumeration with keys equal to their value.
+ *
+ * For example:
+ *
+ * var COLORS = keyMirror({blue: null, red: null});
+ * var myColor = COLORS.blue;
+ * var isColorValid = !!COLORS[myColor];
+ *
+ * The last line could not be performed if the values of the generated enum were
+ * not equal to their keys.
+ *
+ * Input: {key1: val1, key2: val2}
+ * Output: {key1: key1, key2: key2}
+ *
+ * @param {object} obj
+ * @return {object}
+ */
+ var keyMirror = function(obj) {
+ var ret = {};
+ var key;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ obj instanceof Object && !Array.isArray(obj),
+ 'keyMirror(...): Argument must be an object.'
+ ) : invariant(obj instanceof Object && !Array.isArray(obj)));
+ for (key in obj) {
+ if (!obj.hasOwnProperty(key)) {
+ continue;
+ }
+ ret[key] = key;
+ }
+ return ret;
+ };
+
+ module.exports = keyMirror;
+
+
+/***/ },
+/* 58 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule invariant
+ */
+
+ "use strict";
+
+ /**
+ * Use invariant() to assert state which your program assumes to be true.
+ *
+ * Provide sprintf-style format (only %s is supported) and arguments
+ * to provide information about what broke and what you were
+ * expecting.
+ *
+ * The invariant message will be stripped in production, but the invariant
+ * will remain to ensure logic does not differ in production.
+ */
+
+ var invariant = function(condition, format, a, b, c, d, e, f) {
+ if ("production" !== process.env.NODE_ENV) {
+ if (format === undefined) {
+ throw new Error('invariant requires an error message argument');
+ }
+ }
+
+ if (!condition) {
+ var error;
+ if (format === undefined) {
+ 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];
+ var argIndex = 0;
+ error = new Error(
+ 'Invariant Violation: ' +
+ format.replace(/%s/g, function() { return args[argIndex++]; })
+ );
+ }
+
+ error.framesToPop = 1; // we don't care about invariant's own frame
+ throw error;
+ }
+ };
+
+ module.exports = invariant;
+
+
+/***/ },
+/* 59 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactChildren
+ */
+
+ 'use strict';
+
+ var PooledClass = __webpack_require__(60);
+ var ReactFragment = __webpack_require__(61);
+
+ var traverseAllChildren = __webpack_require__(69);
+ var warning = __webpack_require__(66);
+
+ var twoArgumentPooler = PooledClass.twoArgumentPooler;
+ var threeArgumentPooler = PooledClass.threeArgumentPooler;
+
+ /**
+ * PooledClass representing the bookkeeping associated with performing a child
+ * traversal. Allows avoiding binding callbacks.
+ *
+ * @constructor ForEachBookKeeping
+ * @param {!function} forEachFunction Function to perform traversal with.
+ * @param {?*} forEachContext Context to perform context with.
+ */
+ function ForEachBookKeeping(forEachFunction, forEachContext) {
+ this.forEachFunction = forEachFunction;
+ this.forEachContext = forEachContext;
+ }
+ PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
+
+ function forEachSingleChild(traverseContext, child, name, i) {
+ var forEachBookKeeping = traverseContext;
+ forEachBookKeeping.forEachFunction.call(
+ forEachBookKeeping.forEachContext, child, i);
+ }
+
+ /**
+ * Iterates through children that are typically specified as `props.children`.
+ *
+ * The provided forEachFunc(child, index) will be called for each
+ * leaf child.
+ *
+ * @param {?*} children Children tree container.
+ * @param {function(*, int)} forEachFunc.
+ * @param {*} forEachContext Context for forEachContext.
+ */
+ function forEachChildren(children, forEachFunc, forEachContext) {
+ if (children == null) {
+ return children;
+ }
+
+ var traverseContext =
+ ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
+ traverseAllChildren(children, forEachSingleChild, traverseContext);
+ ForEachBookKeeping.release(traverseContext);
+ }
+
+ /**
+ * PooledClass representing the bookkeeping associated with performing a child
+ * mapping. Allows avoiding binding callbacks.
+ *
+ * @constructor MapBookKeeping
+ * @param {!*} mapResult Object containing the ordered map of results.
+ * @param {!function} mapFunction Function to perform mapping with.
+ * @param {?*} mapContext Context to perform mapping with.
+ */
+ function MapBookKeeping(mapResult, mapFunction, mapContext) {
+ this.mapResult = mapResult;
+ this.mapFunction = mapFunction;
+ this.mapContext = mapContext;
+ }
+ PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
+
+ function mapSingleChildIntoContext(traverseContext, child, name, i) {
+ var mapBookKeeping = traverseContext;
+ var mapResult = mapBookKeeping.mapResult;
+
+ var keyUnique = !mapResult.hasOwnProperty(name);
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ keyUnique,
+ 'ReactChildren.map(...): Encountered two children with the same key, ' +
+ '`%s`. Child keys must be unique; when two children share a key, only ' +
+ 'the first child will be used.',
+ name
+ ) : null);
+ }
+
+ if (keyUnique) {
+ var mappedChild =
+ mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
+ mapResult[name] = mappedChild;
+ }
+ }
+
+ /**
+ * Maps children that are typically specified as `props.children`.
+ *
+ * The provided mapFunction(child, key, index) will be called for each
+ * leaf child.
+ *
+ * TODO: This may likely break any calls to `ReactChildren.map` that were
+ * previously relying on the fact that we guarded against null children.
+ *
+ * @param {?*} children Children tree container.
+ * @param {function(*, int)} mapFunction.
+ * @param {*} mapContext Context for mapFunction.
+ * @return {object} Object containing the ordered map of results.
+ */
+ function mapChildren(children, func, context) {
+ if (children == null) {
+ return children;
+ }
+
+ var mapResult = {};
+ var traverseContext = MapBookKeeping.getPooled(mapResult, func, context);
+ traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
+ MapBookKeeping.release(traverseContext);
+ return ReactFragment.create(mapResult);
+ }
+
+ function forEachSingleChildDummy(traverseContext, child, name, i) {
+ return null;
+ }
+
+ /**
+ * Count the number of children that are typically specified as
+ * `props.children`.
+ *
+ * @param {?*} children Children tree container.
+ * @return {number} The number of children.
+ */
+ function countChildren(children, context) {
+ return traverseAllChildren(children, forEachSingleChildDummy, null);
+ }
+
+ var ReactChildren = {
+ forEach: forEachChildren,
+ map: mapChildren,
+ count: countChildren
+ };
+
+ module.exports = ReactChildren;
+
+
+/***/ },
+/* 60 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule PooledClass
+ */
+
+ 'use strict';
+
+ var invariant = __webpack_require__(58);
+
+ /**
+ * Static poolers. Several custom versions for each potential number of
+ * arguments. A completely generic pooler is easy to implement, but would
+ * require accessing the `arguments` object. In each of these, `this` refers to
+ * the Class itself, not an instance. If any others are needed, simply add them
+ * here, or in their own files.
+ */
+ var oneArgumentPooler = function(copyFieldsFrom) {
+ var Klass = this;
+ if (Klass.instancePool.length) {
+ var instance = Klass.instancePool.pop();
+ Klass.call(instance, copyFieldsFrom);
+ return instance;
+ } else {
+ return new Klass(copyFieldsFrom);
+ }
+ };
+
+ var twoArgumentPooler = function(a1, a2) {
+ var Klass = this;
+ if (Klass.instancePool.length) {
+ var instance = Klass.instancePool.pop();
+ Klass.call(instance, a1, a2);
+ return instance;
+ } else {
+ return new Klass(a1, a2);
+ }
+ };
+
+ var threeArgumentPooler = function(a1, a2, a3) {
+ var Klass = this;
+ if (Klass.instancePool.length) {
+ var instance = Klass.instancePool.pop();
+ Klass.call(instance, a1, a2, a3);
+ return instance;
+ } else {
+ return new Klass(a1, a2, a3);
+ }
+ };
+
+ var fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
+ var Klass = this;
+ if (Klass.instancePool.length) {
+ var instance = Klass.instancePool.pop();
+ Klass.call(instance, a1, a2, a3, a4, a5);
+ return instance;
+ } else {
+ return new Klass(a1, a2, a3, a4, a5);
+ }
+ };
+
+ var standardReleaser = function(instance) {
+ var Klass = this;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ instance instanceof Klass,
+ 'Trying to release an instance into a pool of a different type.'
+ ) : invariant(instance instanceof Klass));
+ if (instance.destructor) {
+ instance.destructor();
+ }
+ if (Klass.instancePool.length < Klass.poolSize) {
+ Klass.instancePool.push(instance);
+ }
+ };
+
+ var DEFAULT_POOL_SIZE = 10;
+ var DEFAULT_POOLER = oneArgumentPooler;
+
+ /**
+ * Augments `CopyConstructor` to be a poolable class, augmenting only the class
+ * itself (statically) not adding any prototypical fields. Any CopyConstructor
+ * you give this may have a `poolSize` property, and will look for a
+ * prototypical `destructor` on instances (optional).
+ *
+ * @param {Function} CopyConstructor Constructor that can be used to reset.
+ * @param {Function} pooler Customizable pooler.
+ */
+ var addPoolingTo = function(CopyConstructor, pooler) {
+ var NewKlass = CopyConstructor;
+ NewKlass.instancePool = [];
+ NewKlass.getPooled = pooler || DEFAULT_POOLER;
+ if (!NewKlass.poolSize) {
+ NewKlass.poolSize = DEFAULT_POOL_SIZE;
+ }
+ NewKlass.release = standardReleaser;
+ return NewKlass;
+ };
+
+ var PooledClass = {
+ addPoolingTo: addPoolingTo,
+ oneArgumentPooler: oneArgumentPooler,
+ twoArgumentPooler: twoArgumentPooler,
+ threeArgumentPooler: threeArgumentPooler,
+ fiveArgumentPooler: fiveArgumentPooler
+ };
+
+ module.exports = PooledClass;
+
+
+/***/ },
+/* 61 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactFragment
+ */
+
+ 'use strict';
+
+ var ReactElement = __webpack_require__(62);
+
+ var warning = __webpack_require__(66);
+
+ /**
+ * We used to allow keyed objects to serve as a collection of ReactElements,
+ * or nested sets. This allowed us a way to explicitly key a set a fragment of
+ * components. This is now being replaced with an opaque data structure.
+ * The upgrade path is to call React.addons.createFragment({ key: value }) to
+ * create a keyed fragment. The resulting data structure is opaque, for now.
+ */
+
+ if ("production" !== process.env.NODE_ENV) {
+ var fragmentKey = '_reactFragment';
+ var didWarnKey = '_reactDidWarn';
+ var canWarnForReactFragment = false;
+
+ try {
+ // Feature test. Don't even try to issue this warning if we can't use
+ // enumerable: false.
+
+ var dummy = function() {
+ return 1;
+ };
+
+ Object.defineProperty(
+ {},
+ fragmentKey,
+ {enumerable: false, value: true}
+ );
+
+ Object.defineProperty(
+ {},
+ 'key',
+ {enumerable: true, get: dummy}
+ );
+
+ canWarnForReactFragment = true;
+ } catch (x) { }
+
+ var proxyPropertyAccessWithWarning = function(obj, key) {
+ Object.defineProperty(obj, key, {
+ enumerable: true,
+ get: function() {
+ ("production" !== process.env.NODE_ENV ? warning(
+ this[didWarnKey],
+ 'A ReactFragment is an opaque type. Accessing any of its ' +
+ 'properties is deprecated. Pass it to one of the React.Children ' +
+ 'helpers.'
+ ) : null);
+ this[didWarnKey] = true;
+ return this[fragmentKey][key];
+ },
+ set: function(value) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ this[didWarnKey],
+ 'A ReactFragment is an immutable opaque type. Mutating its ' +
+ 'properties is deprecated.'
+ ) : null);
+ this[didWarnKey] = true;
+ this[fragmentKey][key] = value;
+ }
+ });
+ };
+
+ var issuedWarnings = {};
+
+ var didWarnForFragment = function(fragment) {
+ // We use the keys and the type of the value as a heuristic to dedupe the
+ // warning to avoid spamming too much.
+ var fragmentCacheKey = '';
+ for (var key in fragment) {
+ fragmentCacheKey += key + ':' + (typeof fragment[key]) + ',';
+ }
+ var alreadyWarnedOnce = !!issuedWarnings[fragmentCacheKey];
+ issuedWarnings[fragmentCacheKey] = true;
+ return alreadyWarnedOnce;
+ };
+ }
+
+ var ReactFragment = {
+ // Wrap a keyed object in an opaque proxy that warns you if you access any
+ // of its properties.
+ create: function(object) {
+ if ("production" !== process.env.NODE_ENV) {
+ if (typeof object !== 'object' || !object || Array.isArray(object)) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'React.addons.createFragment only accepts a single object.',
+ object
+ ) : null);
+ return object;
+ }
+ if (ReactElement.isValidElement(object)) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'React.addons.createFragment does not accept a ReactElement ' +
+ 'without a wrapper object.'
+ ) : null);
+ return object;
+ }
+ if (canWarnForReactFragment) {
+ var proxy = {};
+ Object.defineProperty(proxy, fragmentKey, {
+ enumerable: false,
+ value: object
+ });
+ Object.defineProperty(proxy, didWarnKey, {
+ writable: true,
+ enumerable: false,
+ value: false
+ });
+ for (var key in object) {
+ proxyPropertyAccessWithWarning(proxy, key);
+ }
+ Object.preventExtensions(proxy);
+ return proxy;
+ }
+ }
+ return object;
+ },
+ // Extract the original keyed object from the fragment opaque type. Warn if
+ // a plain object is passed here.
+ extract: function(fragment) {
+ if ("production" !== process.env.NODE_ENV) {
+ if (canWarnForReactFragment) {
+ if (!fragment[fragmentKey]) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ didWarnForFragment(fragment),
+ 'Any use of a keyed object should be wrapped in ' +
+ 'React.addons.createFragment(object) before being passed as a ' +
+ 'child.'
+ ) : null);
+ return fragment;
+ }
+ return fragment[fragmentKey];
+ }
+ }
+ return fragment;
+ },
+ // Check if this is a fragment and if so, extract the keyed object. If it
+ // is a fragment-like object, warn that it should be wrapped. Ignore if we
+ // can't determine what kind of object this is.
+ extractIfFragment: function(fragment) {
+ if ("production" !== process.env.NODE_ENV) {
+ if (canWarnForReactFragment) {
+ // If it is the opaque type, return the keyed object.
+ if (fragment[fragmentKey]) {
+ return fragment[fragmentKey];
+ }
+ // Otherwise, check each property if it has an element, if it does
+ // it is probably meant as a fragment, so we can warn early. Defer,
+ // the warning to extract.
+ for (var key in fragment) {
+ if (fragment.hasOwnProperty(key) &&
+ ReactElement.isValidElement(fragment[key])) {
+ // This looks like a fragment object, we should provide an
+ // early warning.
+ return ReactFragment.extract(fragment);
+ }
+ }
+ }
+ }
+ return fragment;
+ }
+ };
+
+ module.exports = ReactFragment;
+
+
+/***/ },
+/* 62 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactElement
+ */
+
+ 'use strict';
+
+ var ReactContext = __webpack_require__(63);
+ var ReactCurrentOwner = __webpack_require__(68);
+
+ var assign = __webpack_require__(64);
+ var warning = __webpack_require__(66);
+
+ var RESERVED_PROPS = {
+ key: true,
+ ref: true
+ };
+
+ /**
+ * Warn for mutations.
+ *
+ * @internal
+ * @param {object} object
+ * @param {string} key
+ */
+ function defineWarningProperty(object, key) {
+ Object.defineProperty(object, key, {
+
+ configurable: false,
+ enumerable: true,
+
+ get: function() {
+ if (!this._store) {
+ return null;
+ }
+ return this._store[key];
+ },
+
+ set: function(value) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'Don\'t set the %s property of the React element. Instead, ' +
+ 'specify the correct value when initially creating the element.',
+ key
+ ) : null);
+ this._store[key] = value;
+ }
+
+ });
+ }
+
+ /**
+ * This is updated to true if the membrane is successfully created.
+ */
+ var useMutationMembrane = false;
+
+ /**
+ * Warn for mutations.
+ *
+ * @internal
+ * @param {object} element
+ */
+ function defineMutationMembrane(prototype) {
+ try {
+ var pseudoFrozenProperties = {
+ props: true
+ };
+ for (var key in pseudoFrozenProperties) {
+ defineWarningProperty(prototype, key);
+ }
+ useMutationMembrane = true;
+ } catch (x) {
+ // IE will fail on defineProperty
+ }
+ }
+
+ /**
+ * Base constructor for all React elements. This is only used to make this
+ * work with a dynamic instanceof check. Nothing should live on this prototype.
+ *
+ * @param {*} type
+ * @param {string|object} ref
+ * @param {*} key
+ * @param {*} props
+ * @internal
+ */
+ var ReactElement = function(type, key, ref, owner, context, props) {
+ // Built-in properties that belong on the element
+ this.type = type;
+ this.key = key;
+ this.ref = ref;
+
+ // Record the component responsible for creating this element.
+ this._owner = owner;
+
+ // TODO: Deprecate withContext, and then the context becomes accessible
+ // through the owner.
+ this._context = context;
+
+ if ("production" !== process.env.NODE_ENV) {
+ // The validation flag and props are currently mutative. We put them on
+ // an external backing store so that we can freeze the whole object.
+ // This can be replaced with a WeakMap once they are implemented in
+ // commonly used development environments.
+ this._store = {props: props, originalProps: assign({}, props)};
+
+ // To make comparing ReactElements easier for testing purposes, we make
+ // the validation flag non-enumerable (where possible, which should
+ // include every environment we run tests in), so the test framework
+ // ignores it.
+ try {
+ Object.defineProperty(this._store, 'validated', {
+ configurable: false,
+ enumerable: false,
+ writable: true
+ });
+ } catch (x) {
+ }
+ this._store.validated = false;
+
+ // We're not allowed to set props directly on the object so we early
+ // return and rely on the prototype membrane to forward to the backing
+ // store.
+ if (useMutationMembrane) {
+ Object.freeze(this);
+ return;
+ }
+ }
+
+ this.props = props;
+ };
+
+ // We intentionally don't expose the function on the constructor property.
+ // ReactElement should be indistinguishable from a plain object.
+ ReactElement.prototype = {
+ _isReactElement: true
+ };
+
+ if ("production" !== process.env.NODE_ENV) {
+ defineMutationMembrane(ReactElement.prototype);
+ }
+
+ ReactElement.createElement = function(type, config, children) {
+ var propName;
+
+ // Reserved names are extracted
+ var props = {};
+
+ var key = null;
+ var ref = null;
+
+ if (config != null) {
+ ref = config.ref === undefined ? null : config.ref;
+ key = config.key === undefined ? null : '' + config.key;
+ // Remaining properties are added to a new props object
+ for (propName in config) {
+ if (config.hasOwnProperty(propName) &&
+ !RESERVED_PROPS.hasOwnProperty(propName)) {
+ props[propName] = config[propName];
+ }
+ }
+ }
+
+ // Children can be more than one argument, and those are transferred onto
+ // the newly allocated props object.
+ var childrenLength = arguments.length - 2;
+ if (childrenLength === 1) {
+ props.children = children;
+ } else if (childrenLength > 1) {
+ var childArray = Array(childrenLength);
+ for (var i = 0; i < childrenLength; i++) {
+ childArray[i] = arguments[i + 2];
+ }
+ props.children = childArray;
+ }
+
+ // Resolve default props
+ if (type && type.defaultProps) {
+ var defaultProps = type.defaultProps;
+ for (propName in defaultProps) {
+ if (typeof props[propName] === 'undefined') {
+ props[propName] = defaultProps[propName];
+ }
+ }
+ }
+
+ return new ReactElement(
+ type,
+ key,
+ ref,
+ ReactCurrentOwner.current,
+ ReactContext.current,
+ props
+ );
+ };
+
+ ReactElement.createFactory = function(type) {
+ var factory = ReactElement.createElement.bind(null, type);
+ // Expose the type on the factory and the prototype so that it can be
+ // easily accessed on elements. E.g. .type === Foo.type.
+ // This should not be named `constructor` since this may not be the function
+ // that created the element, and it may not even be a constructor.
+ // Legacy hook TODO: Warn if this is accessed
+ factory.type = type;
+ return factory;
+ };
+
+ ReactElement.cloneAndReplaceProps = function(oldElement, newProps) {
+ var newElement = new ReactElement(
+ oldElement.type,
+ oldElement.key,
+ oldElement.ref,
+ oldElement._owner,
+ oldElement._context,
+ newProps
+ );
+
+ if ("production" !== process.env.NODE_ENV) {
+ // If the key on the original is valid, then the clone is valid
+ newElement._store.validated = oldElement._store.validated;
+ }
+ return newElement;
+ };
+
+ ReactElement.cloneElement = function(element, config, children) {
+ var propName;
+
+ // Original props are copied
+ var props = assign({}, element.props);
+
+ // Reserved names are extracted
+ var key = element.key;
+ var ref = element.ref;
+
+ // Owner will be preserved, unless ref is overridden
+ var owner = element._owner;
+
+ if (config != null) {
+ if (config.ref !== undefined) {
+ // Silently steal the ref from the parent.
+ ref = config.ref;
+ owner = ReactCurrentOwner.current;
+ }
+ if (config.key !== undefined) {
+ key = '' + config.key;
+ }
+ // Remaining properties override existing props
+ for (propName in config) {
+ if (config.hasOwnProperty(propName) &&
+ !RESERVED_PROPS.hasOwnProperty(propName)) {
+ props[propName] = config[propName];
+ }
+ }
+ }
+
+ // Children can be more than one argument, and those are transferred onto
+ // the newly allocated props object.
+ var childrenLength = arguments.length - 2;
+ if (childrenLength === 1) {
+ props.children = children;
+ } else if (childrenLength > 1) {
+ var childArray = Array(childrenLength);
+ for (var i = 0; i < childrenLength; i++) {
+ childArray[i] = arguments[i + 2];
+ }
+ props.children = childArray;
+ }
+
+ return new ReactElement(
+ element.type,
+ key,
+ ref,
+ owner,
+ element._context,
+ props
+ );
+ };
+
+ /**
+ * @param {?object} object
+ * @return {boolean} True if `object` is a valid component.
+ * @final
+ */
+ ReactElement.isValidElement = function(object) {
+ // ReactTestUtils is often used outside of beforeEach where as React is
+ // within it. This leads to two different instances of React on the same
+ // page. To identify a element from a different React instance we use
+ // a flag instead of an instanceof check.
+ var isElement = !!(object && object._isReactElement);
+ // if (isElement && !(object instanceof ReactElement)) {
+ // This is an indicator that you're using multiple versions of React at the
+ // same time. This will screw with ownership and stuff. Fix it, please.
+ // TODO: We could possibly warn here.
+ // }
+ return isElement;
+ };
+
+ module.exports = ReactElement;
+
+
+/***/ },
+/* 63 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactContext
+ */
+
+ 'use strict';
+
+ var assign = __webpack_require__(64);
+ var emptyObject = __webpack_require__(65);
+ var warning = __webpack_require__(66);
+
+ var didWarn = false;
+
+ /**
+ * Keeps track of the current context.
+ *
+ * The context is automatically passed down the component ownership hierarchy
+ * and is accessible via `this.context` on ReactCompositeComponents.
+ */
+ var ReactContext = {
+
+ /**
+ * @internal
+ * @type {object}
+ */
+ current: emptyObject,
+
+ /**
+ * Temporarily extends the current context while executing scopedCallback.
+ *
+ * A typical use case might look like
+ *
+ * render: function() {
+ * var children = ReactContext.withContext({foo: 'foo'}, () => (
+ *
+ * ));
+ * return
{children}
;
+ * }
+ *
+ * @param {object} newContext New context to merge into the existing context
+ * @param {function} scopedCallback Callback to run with the new context
+ * @return {ReactComponent|array}
+ */
+ withContext: function(newContext, scopedCallback) {
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ didWarn,
+ 'withContext is deprecated and will be removed in a future version. ' +
+ 'Use a wrapper component with getChildContext instead.'
+ ) : null);
+
+ didWarn = true;
+ }
+
+ var result;
+ var previousContext = ReactContext.current;
+ ReactContext.current = assign({}, previousContext, newContext);
+ try {
+ result = scopedCallback();
+ } finally {
+ ReactContext.current = previousContext;
+ }
+ return result;
+ }
+
+ };
+
+ module.exports = ReactContext;
+
+
+/***/ },
+/* 64 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule Object.assign
+ */
+
+ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
+
+ 'use strict';
+
+ function assign(target, sources) {
+ if (target == null) {
+ throw new TypeError('Object.assign target cannot be null or undefined');
+ }
+
+ var to = Object(target);
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+ for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
+ var nextSource = arguments[nextIndex];
+ if (nextSource == null) {
+ continue;
+ }
+
+ var from = Object(nextSource);
+
+ // We don't currently support accessors nor proxies. Therefore this
+ // copy cannot throw. If we ever supported this then we must handle
+ // exceptions and side-effects. We don't support symbols so they won't
+ // be transferred.
+
+ for (var key in from) {
+ if (hasOwnProperty.call(from, key)) {
+ to[key] = from[key];
+ }
+ }
+ }
+
+ return to;
+ }
+
+ module.exports = assign;
+
+
+/***/ },
+/* 65 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule emptyObject
+ */
+
+ "use strict";
+
+ var emptyObject = {};
+
+ if ("production" !== process.env.NODE_ENV) {
+ Object.freeze(emptyObject);
+ }
+
+ module.exports = emptyObject;
+
+
+/***/ },
+/* 66 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule warning
+ */
+
+ "use strict";
+
+ var emptyFunction = __webpack_require__(67);
+
+ /**
+ * Similar to invariant but only logs a warning if the condition is not met.
+ * This can be used to log issues in development environments in critical
+ * paths. Removing the logging code for production environments will keep the
+ * same logic and follow the same code paths.
+ */
+
+ var warning = emptyFunction;
+
+ if ("production" !== process.env.NODE_ENV) {
+ warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
+ if (format === undefined) {
+ throw new Error(
+ '`warning(condition, format, ...args)` requires a warning ' +
+ 'message argument'
+ );
+ }
+
+ if (format.length < 10 || /^[s\W]*$/.test(format)) {
+ throw new Error(
+ 'The warning format should be able to uniquely identify this ' +
+ 'warning. Please, use a more descriptive format than: ' + format
+ );
+ }
+
+ if (format.indexOf('Failed Composite propType: ') === 0) {
+ return; // Ignore CompositeComponent proptype check.
+ }
+
+ if (!condition) {
+ var argIndex = 0;
+ var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];});
+ console.warn(message);
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ throw new Error(message);
+ } catch(x) {}
+ }
+ };
+ }
+
+ module.exports = warning;
+
+
+/***/ },
+/* 67 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule emptyFunction
+ */
+
+ function makeEmptyFunction(arg) {
+ return function() {
+ return arg;
+ };
+ }
+
+ /**
+ * This function accepts and discards inputs; it has no side effects. This is
+ * primarily useful idiomatically for overridable function endpoints which
+ * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
+ */
+ function emptyFunction() {}
+
+ emptyFunction.thatReturns = makeEmptyFunction;
+ emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
+ emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
+ emptyFunction.thatReturnsNull = makeEmptyFunction(null);
+ emptyFunction.thatReturnsThis = function() { return this; };
+ emptyFunction.thatReturnsArgument = function(arg) { return arg; };
+
+ module.exports = emptyFunction;
+
+
+/***/ },
+/* 68 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactCurrentOwner
+ */
+
+ 'use strict';
+
+ /**
+ * Keeps track of the current owner.
+ *
+ * The current owner is the component who should own any components that are
+ * currently being constructed.
+ *
+ * The depth indicate how many composite components are above this render level.
+ */
+ var ReactCurrentOwner = {
+
+ /**
+ * @internal
+ * @type {ReactComponent}
+ */
+ current: null
+
+ };
+
+ module.exports = ReactCurrentOwner;
+
+
+/***/ },
+/* 69 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule traverseAllChildren
+ */
+
+ 'use strict';
+
+ var ReactElement = __webpack_require__(62);
+ var ReactFragment = __webpack_require__(61);
+ var ReactInstanceHandles = __webpack_require__(71);
+
+ var getIteratorFn = __webpack_require__(70);
+ var invariant = __webpack_require__(58);
+ var warning = __webpack_require__(66);
+
+ var SEPARATOR = ReactInstanceHandles.SEPARATOR;
+ var SUBSEPARATOR = ':';
+
+ /**
+ * TODO: Test that a single child and an array with one item have the same key
+ * pattern.
+ */
+
+ var userProvidedKeyEscaperLookup = {
+ '=': '=0',
+ '.': '=1',
+ ':': '=2'
+ };
+
+ var userProvidedKeyEscapeRegex = /[=.:]/g;
+
+ var didWarnAboutMaps = false;
+
+ function userProvidedKeyEscaper(match) {
+ return userProvidedKeyEscaperLookup[match];
+ }
+
+ /**
+ * Generate a key string that identifies a component within a set.
+ *
+ * @param {*} component A component that could contain a manual key.
+ * @param {number} index Index that is used if a manual key is not provided.
+ * @return {string}
+ */
+ function getComponentKey(component, index) {
+ if (component && component.key != null) {
+ // Explicit key
+ return wrapUserProvidedKey(component.key);
+ }
+ // Implicit key determined by the index in the set
+ return index.toString(36);
+ }
+
+ /**
+ * Escape a component key so that it is safe to use in a reactid.
+ *
+ * @param {*} key Component key to be escaped.
+ * @return {string} An escaped string.
+ */
+ function escapeUserProvidedKey(text) {
+ return ('' + text).replace(
+ userProvidedKeyEscapeRegex,
+ userProvidedKeyEscaper
+ );
+ }
+
+ /**
+ * Wrap a `key` value explicitly provided by the user to distinguish it from
+ * implicitly-generated keys generated by a component's index in its parent.
+ *
+ * @param {string} key Value of a user-provided `key` attribute
+ * @return {string}
+ */
+ function wrapUserProvidedKey(key) {
+ return '$' + escapeUserProvidedKey(key);
+ }
+
+ /**
+ * @param {?*} children Children tree container.
+ * @param {!string} nameSoFar Name of the key path so far.
+ * @param {!number} indexSoFar Number of children encountered until this point.
+ * @param {!function} callback Callback to invoke with each child found.
+ * @param {?*} traverseContext Used to pass information throughout the traversal
+ * process.
+ * @return {!number} The number of children in this subtree.
+ */
+ function traverseAllChildrenImpl(
+ children,
+ nameSoFar,
+ indexSoFar,
+ callback,
+ traverseContext
+ ) {
+ var type = typeof children;
+
+ if (type === 'undefined' || type === 'boolean') {
+ // All of the above are perceived as null.
+ children = null;
+ }
+
+ if (children === null ||
+ type === 'string' ||
+ type === 'number' ||
+ ReactElement.isValidElement(children)) {
+ callback(
+ traverseContext,
+ children,
+ // If it's the only child, treat the name as if it was wrapped in an array
+ // so that it's consistent if the number of children grows.
+ nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar,
+ indexSoFar
+ );
+ return 1;
+ }
+
+ var child, nextName, nextIndex;
+ var subtreeCount = 0; // Count of children found in the current subtree.
+
+ if (Array.isArray(children)) {
+ for (var i = 0; i < children.length; i++) {
+ child = children[i];
+ nextName = (
+ (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
+ getComponentKey(child, i)
+ );
+ nextIndex = indexSoFar + subtreeCount;
+ subtreeCount += traverseAllChildrenImpl(
+ child,
+ nextName,
+ nextIndex,
+ callback,
+ traverseContext
+ );
+ }
+ } else {
+ var iteratorFn = getIteratorFn(children);
+ if (iteratorFn) {
+ var iterator = iteratorFn.call(children);
+ var step;
+ if (iteratorFn !== children.entries) {
+ var ii = 0;
+ while (!(step = iterator.next()).done) {
+ child = step.value;
+ nextName = (
+ (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
+ getComponentKey(child, ii++)
+ );
+ nextIndex = indexSoFar + subtreeCount;
+ subtreeCount += traverseAllChildrenImpl(
+ child,
+ nextName,
+ nextIndex,
+ callback,
+ traverseContext
+ );
+ }
+ } else {
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ didWarnAboutMaps,
+ 'Using Maps as children is not yet fully supported. It is an ' +
+ 'experimental feature that might be removed. Convert it to a ' +
+ 'sequence / iterable of keyed ReactElements instead.'
+ ) : null);
+ didWarnAboutMaps = true;
+ }
+ // Iterator will provide entry [k,v] tuples rather than values.
+ while (!(step = iterator.next()).done) {
+ var entry = step.value;
+ if (entry) {
+ child = entry[1];
+ nextName = (
+ (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
+ wrapUserProvidedKey(entry[0]) + SUBSEPARATOR +
+ getComponentKey(child, 0)
+ );
+ nextIndex = indexSoFar + subtreeCount;
+ subtreeCount += traverseAllChildrenImpl(
+ child,
+ nextName,
+ nextIndex,
+ callback,
+ traverseContext
+ );
+ }
+ }
+ }
+ } else if (type === 'object') {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ children.nodeType !== 1,
+ 'traverseAllChildren(...): Encountered an invalid child; DOM ' +
+ 'elements are not valid children of React components.'
+ ) : invariant(children.nodeType !== 1));
+ var fragment = ReactFragment.extract(children);
+ for (var key in fragment) {
+ if (fragment.hasOwnProperty(key)) {
+ child = fragment[key];
+ nextName = (
+ (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
+ wrapUserProvidedKey(key) + SUBSEPARATOR +
+ getComponentKey(child, 0)
+ );
+ nextIndex = indexSoFar + subtreeCount;
+ subtreeCount += traverseAllChildrenImpl(
+ child,
+ nextName,
+ nextIndex,
+ callback,
+ traverseContext
+ );
+ }
+ }
+ }
+ }
+
+ return subtreeCount;
+ }
+
+ /**
+ * Traverses children that are typically specified as `props.children`, but
+ * might also be specified through attributes:
+ *
+ * - `traverseAllChildren(this.props.children, ...)`
+ * - `traverseAllChildren(this.props.leftPanelChildren, ...)`
+ *
+ * The `traverseContext` is an optional argument that is passed through the
+ * entire traversal. It can be used to store accumulations or anything else that
+ * the callback might find relevant.
+ *
+ * @param {?*} children Children tree object.
+ * @param {!function} callback To invoke upon traversing each child.
+ * @param {?*} traverseContext Context for traversal.
+ * @return {!number} The number of children in this subtree.
+ */
+ function traverseAllChildren(children, callback, traverseContext) {
+ if (children == null) {
+ return 0;
+ }
+
+ return traverseAllChildrenImpl(children, '', 0, callback, traverseContext);
+ }
+
+ module.exports = traverseAllChildren;
+
+
+/***/ },
+/* 70 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule getIteratorFn
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ /* global Symbol */
+ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
+ var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
+
+ /**
+ * Returns the iterator method function contained on the iterable object.
+ *
+ * Be sure to invoke the function with the iterable as context:
+ *
+ * var iteratorFn = getIteratorFn(myIterable);
+ * if (iteratorFn) {
+ * var iterator = iteratorFn.call(myIterable);
+ * ...
+ * }
+ *
+ * @param {?object} maybeIterable
+ * @return {?function}
+ */
+ function getIteratorFn(maybeIterable) {
+ var iteratorFn = maybeIterable && (
+ (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL])
+ );
+ if (typeof iteratorFn === 'function') {
+ return iteratorFn;
+ }
+ }
+
+ module.exports = getIteratorFn;
+
+
+/***/ },
+/* 71 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactInstanceHandles
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ var ReactRootIndex = __webpack_require__(72);
+
+ var invariant = __webpack_require__(58);
+
+ var SEPARATOR = '.';
+ var SEPARATOR_LENGTH = SEPARATOR.length;
+
+ /**
+ * Maximum depth of traversals before we consider the possibility of a bad ID.
+ */
+ var MAX_TREE_DEPTH = 100;
+
+ /**
+ * Creates a DOM ID prefix to use when mounting React components.
+ *
+ * @param {number} index A unique integer
+ * @return {string} React root ID.
+ * @internal
+ */
+ function getReactRootIDString(index) {
+ return SEPARATOR + index.toString(36);
+ }
+
+ /**
+ * Checks if a character in the supplied ID is a separator or the end.
+ *
+ * @param {string} id A React DOM ID.
+ * @param {number} index Index of the character to check.
+ * @return {boolean} True if the character is a separator or end of the ID.
+ * @private
+ */
+ function isBoundary(id, index) {
+ return id.charAt(index) === SEPARATOR || index === id.length;
+ }
+
+ /**
+ * Checks if the supplied string is a valid React DOM ID.
+ *
+ * @param {string} id A React DOM ID, maybe.
+ * @return {boolean} True if the string is a valid React DOM ID.
+ * @private
+ */
+ function isValidID(id) {
+ return id === '' || (
+ id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
+ );
+ }
+
+ /**
+ * Checks if the first ID is an ancestor of or equal to the second ID.
+ *
+ * @param {string} ancestorID
+ * @param {string} descendantID
+ * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
+ * @internal
+ */
+ function isAncestorIDOf(ancestorID, descendantID) {
+ return (
+ descendantID.indexOf(ancestorID) === 0 &&
+ isBoundary(descendantID, ancestorID.length)
+ );
+ }
+
+ /**
+ * Gets the parent ID of the supplied React DOM ID, `id`.
+ *
+ * @param {string} id ID of a component.
+ * @return {string} ID of the parent, or an empty string.
+ * @private
+ */
+ function getParentID(id) {
+ return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
+ }
+
+ /**
+ * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
+ * supplied `destinationID`. If they are equal, the ID is returned.
+ *
+ * @param {string} ancestorID ID of an ancestor node of `destinationID`.
+ * @param {string} destinationID ID of the destination node.
+ * @return {string} Next ID on the path from `ancestorID` to `destinationID`.
+ * @private
+ */
+ function getNextDescendantID(ancestorID, destinationID) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ isValidID(ancestorID) && isValidID(destinationID),
+ 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
+ ancestorID,
+ destinationID
+ ) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ isAncestorIDOf(ancestorID, destinationID),
+ 'getNextDescendantID(...): React has made an invalid assumption about ' +
+ 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
+ ancestorID,
+ destinationID
+ ) : invariant(isAncestorIDOf(ancestorID, destinationID)));
+ if (ancestorID === destinationID) {
+ return ancestorID;
+ }
+ // Skip over the ancestor and the immediate separator. Traverse until we hit
+ // another separator or we reach the end of `destinationID`.
+ var start = ancestorID.length + SEPARATOR_LENGTH;
+ var i;
+ for (i = start; i < destinationID.length; i++) {
+ if (isBoundary(destinationID, i)) {
+ break;
+ }
+ }
+ return destinationID.substr(0, i);
+ }
+
+ /**
+ * Gets the nearest common ancestor ID of two IDs.
+ *
+ * Using this ID scheme, the nearest common ancestor ID is the longest common
+ * prefix of the two IDs that immediately preceded a "marker" in both strings.
+ *
+ * @param {string} oneID
+ * @param {string} twoID
+ * @return {string} Nearest common ancestor ID, or the empty string if none.
+ * @private
+ */
+ function getFirstCommonAncestorID(oneID, twoID) {
+ var minLength = Math.min(oneID.length, twoID.length);
+ if (minLength === 0) {
+ return '';
+ }
+ var lastCommonMarkerIndex = 0;
+ // Use `<=` to traverse until the "EOL" of the shorter string.
+ for (var i = 0; i <= minLength; i++) {
+ if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
+ lastCommonMarkerIndex = i;
+ } else if (oneID.charAt(i) !== twoID.charAt(i)) {
+ break;
+ }
+ }
+ var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
+ ("production" !== process.env.NODE_ENV ? invariant(
+ isValidID(longestCommonID),
+ 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
+ oneID,
+ twoID,
+ longestCommonID
+ ) : invariant(isValidID(longestCommonID)));
+ return longestCommonID;
+ }
+
+ /**
+ * Traverses the parent path between two IDs (either up or down). The IDs must
+ * not be the same, and there must exist a parent path between them. If the
+ * callback returns `false`, traversal is stopped.
+ *
+ * @param {?string} start ID at which to start traversal.
+ * @param {?string} stop ID at which to end traversal.
+ * @param {function} cb Callback to invoke each ID with.
+ * @param {?boolean} skipFirst Whether or not to skip the first node.
+ * @param {?boolean} skipLast Whether or not to skip the last node.
+ * @private
+ */
+ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
+ start = start || '';
+ stop = stop || '';
+ ("production" !== process.env.NODE_ENV ? invariant(
+ start !== stop,
+ 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
+ start
+ ) : invariant(start !== stop));
+ var traverseUp = isAncestorIDOf(stop, start);
+ ("production" !== process.env.NODE_ENV ? invariant(
+ traverseUp || isAncestorIDOf(start, stop),
+ 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
+ 'not have a parent path.',
+ start,
+ stop
+ ) : invariant(traverseUp || isAncestorIDOf(start, stop)));
+ // Traverse from `start` to `stop` one depth at a time.
+ var depth = 0;
+ var traverse = traverseUp ? getParentID : getNextDescendantID;
+ for (var id = start; /* until break */; id = traverse(id, stop)) {
+ var ret;
+ if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
+ ret = cb(id, traverseUp, arg);
+ }
+ if (ret === false || id === stop) {
+ // Only break //after// visiting `stop`.
+ break;
+ }
+ ("production" !== process.env.NODE_ENV ? invariant(
+ depth++ < MAX_TREE_DEPTH,
+ 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
+ 'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
+ start, stop
+ ) : invariant(depth++ < MAX_TREE_DEPTH));
+ }
+ }
+
+ /**
+ * Manages the IDs assigned to DOM representations of React components. This
+ * uses a specific scheme in order to traverse the DOM efficiently (e.g. in
+ * order to simulate events).
+ *
+ * @internal
+ */
+ var ReactInstanceHandles = {
+
+ /**
+ * Constructs a React root ID
+ * @return {string} A React root ID.
+ */
+ createReactRootID: function() {
+ return getReactRootIDString(ReactRootIndex.createReactRootIndex());
+ },
+
+ /**
+ * Constructs a React ID by joining a root ID with a name.
+ *
+ * @param {string} rootID Root ID of a parent component.
+ * @param {string} name A component's name (as flattened children).
+ * @return {string} A React ID.
+ * @internal
+ */
+ createReactID: function(rootID, name) {
+ return rootID + name;
+ },
+
+ /**
+ * Gets the DOM ID of the React component that is the root of the tree that
+ * contains the React component with the supplied DOM ID.
+ *
+ * @param {string} id DOM ID of a React component.
+ * @return {?string} DOM ID of the React component that is the root.
+ * @internal
+ */
+ getReactRootIDFromNodeID: function(id) {
+ if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
+ var index = id.indexOf(SEPARATOR, 1);
+ return index > -1 ? id.substr(0, index) : id;
+ }
+ return null;
+ },
+
+ /**
+ * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
+ * should would receive a `mouseEnter` or `mouseLeave` event.
+ *
+ * NOTE: Does not invoke the callback on the nearest common ancestor because
+ * nothing "entered" or "left" that element.
+ *
+ * @param {string} leaveID ID being left.
+ * @param {string} enterID ID being entered.
+ * @param {function} cb Callback to invoke on each entered/left ID.
+ * @param {*} upArg Argument to invoke the callback with on left IDs.
+ * @param {*} downArg Argument to invoke the callback with on entered IDs.
+ * @internal
+ */
+ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
+ var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
+ if (ancestorID !== leaveID) {
+ traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
+ }
+ if (ancestorID !== enterID) {
+ traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
+ }
+ },
+
+ /**
+ * Simulates the traversal of a two-phase, capture/bubble event dispatch.
+ *
+ * NOTE: This traversal happens on IDs without touching the DOM.
+ *
+ * @param {string} targetID ID of the target node.
+ * @param {function} cb Callback to invoke.
+ * @param {*} arg Argument to invoke the callback with.
+ * @internal
+ */
+ traverseTwoPhase: function(targetID, cb, arg) {
+ if (targetID) {
+ traverseParentPath('', targetID, cb, arg, true, false);
+ traverseParentPath(targetID, '', cb, arg, false, true);
+ }
+ },
+
+ /**
+ * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
+ * example, passing `.0.$row-0.1` would result in `cb` getting called
+ * with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
+ *
+ * NOTE: This traversal happens on IDs without touching the DOM.
+ *
+ * @param {string} targetID ID of the target node.
+ * @param {function} cb Callback to invoke.
+ * @param {*} arg Argument to invoke the callback with.
+ * @internal
+ */
+ traverseAncestors: function(targetID, cb, arg) {
+ traverseParentPath('', targetID, cb, arg, true, false);
+ },
+
+ /**
+ * Exposed for unit testing.
+ * @private
+ */
+ _getFirstCommonAncestorID: getFirstCommonAncestorID,
+
+ /**
+ * Exposed for unit testing.
+ * @private
+ */
+ _getNextDescendantID: getNextDescendantID,
+
+ isAncestorIDOf: isAncestorIDOf,
+
+ SEPARATOR: SEPARATOR
+
+ };
+
+ module.exports = ReactInstanceHandles;
+
+
+/***/ },
+/* 72 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactRootIndex
+ * @typechecks
+ */
+
+ 'use strict';
+
+ var ReactRootIndexInjection = {
+ /**
+ * @param {function} _createReactRootIndex
+ */
+ injectCreateReactRootIndex: function(_createReactRootIndex) {
+ ReactRootIndex.createReactRootIndex = _createReactRootIndex;
+ }
+ };
+
+ var ReactRootIndex = {
+ createReactRootIndex: null,
+ injection: ReactRootIndexInjection
+ };
+
+ module.exports = ReactRootIndex;
+
+
+/***/ },
+/* 73 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactComponent
+ */
+
+ 'use strict';
+
+ var ReactUpdateQueue = __webpack_require__(74);
+
+ var invariant = __webpack_require__(58);
+ var warning = __webpack_require__(66);
+
+ /**
+ * Base class helpers for the updating state of a component.
+ */
+ function ReactComponent(props, context) {
+ this.props = props;
+ this.context = context;
+ }
+
+ /**
+ * Sets a subset of the state. Always use this to mutate
+ * state. You should treat `this.state` as immutable.
+ *
+ * There is no guarantee that `this.state` will be immediately updated, so
+ * accessing `this.state` after calling this method may return the old value.
+ *
+ * There is no guarantee that calls to `setState` will run synchronously,
+ * as they may eventually be batched together. You can provide an optional
+ * callback that will be executed when the call to setState is actually
+ * completed.
+ *
+ * When a function is provided to setState, it will be called at some point in
+ * the future (not synchronously). It will be called with the up to date
+ * component arguments (state, props, context). These values can be different
+ * from this.* because your function may be called after receiveProps but before
+ * shouldComponentUpdate, and this new state, props, and context will not yet be
+ * assigned to this.
+ *
+ * @param {object|function} partialState Next partial state or function to
+ * produce next partial state to be merged with current state.
+ * @param {?function} callback Called after state is updated.
+ * @final
+ * @protected
+ */
+ ReactComponent.prototype.setState = function(partialState, callback) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof partialState === 'object' ||
+ typeof partialState === 'function' ||
+ partialState == null,
+ 'setState(...): takes an object of state variables to update or a ' +
+ 'function which returns an object of state variables.'
+ ) : invariant(typeof partialState === 'object' ||
+ typeof partialState === 'function' ||
+ partialState == null));
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ partialState != null,
+ 'setState(...): You passed an undefined or null state object; ' +
+ 'instead, use forceUpdate().'
+ ) : null);
+ }
+ ReactUpdateQueue.enqueueSetState(this, partialState);
+ if (callback) {
+ ReactUpdateQueue.enqueueCallback(this, callback);
+ }
+ };
+
+ /**
+ * Forces an update. This should only be invoked when it is known with
+ * certainty that we are **not** in a DOM transaction.
+ *
+ * You may want to call this when you know that some deeper aspect of the
+ * component's state has changed but `setState` was not called.
+ *
+ * This will not invoke `shouldComponentUpdate`, but it will invoke
+ * `componentWillUpdate` and `componentDidUpdate`.
+ *
+ * @param {?function} callback Called after update is complete.
+ * @final
+ * @protected
+ */
+ ReactComponent.prototype.forceUpdate = function(callback) {
+ ReactUpdateQueue.enqueueForceUpdate(this);
+ if (callback) {
+ ReactUpdateQueue.enqueueCallback(this, callback);
+ }
+ };
+
+ /**
+ * Deprecated APIs. These APIs used to exist on classic React classes but since
+ * we would like to deprecate them, we're not going to move them over to this
+ * modern base class. Instead, we define a getter that warns if it's accessed.
+ */
+ if ("production" !== process.env.NODE_ENV) {
+ var deprecatedAPIs = {
+ getDOMNode: [
+ 'getDOMNode',
+ 'Use React.findDOMNode(component) instead.'
+ ],
+ isMounted: [
+ 'isMounted',
+ 'Instead, make sure to clean up subscriptions and pending requests in ' +
+ 'componentWillUnmount to prevent memory leaks.'
+ ],
+ replaceProps: [
+ 'replaceProps',
+ 'Instead, call React.render again at the top level.'
+ ],
+ replaceState: [
+ 'replaceState',
+ 'Refactor your code to use setState instead (see ' +
+ 'https://github.com/facebook/react/issues/3236).'
+ ],
+ setProps: [
+ 'setProps',
+ 'Instead, call React.render again at the top level.'
+ ]
+ };
+ var defineDeprecationWarning = function(methodName, info) {
+ try {
+ Object.defineProperty(ReactComponent.prototype, methodName, {
+ get: function() {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ '%s(...) is deprecated in plain JavaScript React classes. %s',
+ info[0],
+ info[1]
+ ) : null);
+ return undefined;
+ }
+ });
+ } catch (x) {
+ // IE will fail on defineProperty (es5-shim/sham too)
+ }
+ };
+ for (var fnName in deprecatedAPIs) {
+ if (deprecatedAPIs.hasOwnProperty(fnName)) {
+ defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
+ }
+ }
+ }
+
+ module.exports = ReactComponent;
+
+
+/***/ },
+/* 74 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactUpdateQueue
+ */
+
+ 'use strict';
+
+ var ReactLifeCycle = __webpack_require__(86);
+ var ReactCurrentOwner = __webpack_require__(68);
+ var ReactElement = __webpack_require__(62);
+ var ReactInstanceMap = __webpack_require__(87);
+ var ReactUpdates = __webpack_require__(75);
+
+ var assign = __webpack_require__(64);
+ var invariant = __webpack_require__(58);
+ var warning = __webpack_require__(66);
+
+ function enqueueUpdate(internalInstance) {
+ if (internalInstance !== ReactLifeCycle.currentlyMountingInstance) {
+ // If we're in a componentWillMount handler, don't enqueue a rerender
+ // because ReactUpdates assumes we're in a browser context (which is
+ // wrong for server rendering) and we're about to do a render anyway.
+ // See bug in #1740.
+ ReactUpdates.enqueueUpdate(internalInstance);
+ }
+ }
+
+ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ ReactCurrentOwner.current == null,
+ '%s(...): Cannot update during an existing state transition ' +
+ '(such as within `render`). Render methods should be a pure function ' +
+ 'of props and state.',
+ callerName
+ ) : invariant(ReactCurrentOwner.current == null));
+
+ var internalInstance = ReactInstanceMap.get(publicInstance);
+ if (!internalInstance) {
+ if ("production" !== process.env.NODE_ENV) {
+ // Only warn when we have a callerName. Otherwise we should be silent.
+ // We're probably calling from enqueueCallback. We don't want to warn
+ // there because we already warned for the corresponding lifecycle method.
+ ("production" !== process.env.NODE_ENV ? warning(
+ !callerName,
+ '%s(...): Can only update a mounted or mounting component. ' +
+ 'This usually means you called %s() on an unmounted ' +
+ 'component. This is a no-op.',
+ callerName,
+ callerName
+ ) : null);
+ }
+ return null;
+ }
+
+ if (internalInstance === ReactLifeCycle.currentlyUnmountingInstance) {
+ return null;
+ }
+
+ return internalInstance;
+ }
+
+ /**
+ * ReactUpdateQueue allows for state updates to be scheduled into a later
+ * reconciliation step.
+ */
+ var ReactUpdateQueue = {
+
+ /**
+ * Enqueue a callback that will be executed after all the pending updates
+ * have processed.
+ *
+ * @param {ReactClass} publicInstance The instance to use as `this` context.
+ * @param {?function} callback Called after state is updated.
+ * @internal
+ */
+ enqueueCallback: function(publicInstance, callback) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof callback === 'function',
+ 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' +
+ '`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
+ 'isn\'t callable.'
+ ) : invariant(typeof callback === 'function'));
+ var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
+
+ // Previously we would throw an error if we didn't have an internal
+ // instance. Since we want to make it a no-op instead, we mirror the same
+ // behavior we have in other enqueue* methods.
+ // We also need to ignore callbacks in componentWillMount. See
+ // enqueueUpdates.
+ if (!internalInstance ||
+ internalInstance === ReactLifeCycle.currentlyMountingInstance) {
+ return null;
+ }
+
+ if (internalInstance._pendingCallbacks) {
+ internalInstance._pendingCallbacks.push(callback);
+ } else {
+ internalInstance._pendingCallbacks = [callback];
+ }
+ // TODO: The callback here is ignored when setState is called from
+ // componentWillMount. Either fix it or disallow doing so completely in
+ // favor of getInitialState. Alternatively, we can disallow
+ // componentWillMount during server-side rendering.
+ enqueueUpdate(internalInstance);
+ },
+
+ enqueueCallbackInternal: function(internalInstance, callback) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof callback === 'function',
+ 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' +
+ '`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
+ 'isn\'t callable.'
+ ) : invariant(typeof callback === 'function'));
+ if (internalInstance._pendingCallbacks) {
+ internalInstance._pendingCallbacks.push(callback);
+ } else {
+ internalInstance._pendingCallbacks = [callback];
+ }
+ enqueueUpdate(internalInstance);
+ },
+
+ /**
+ * Forces an update. This should only be invoked when it is known with
+ * certainty that we are **not** in a DOM transaction.
+ *
+ * You may want to call this when you know that some deeper aspect of the
+ * component's state has changed but `setState` was not called.
+ *
+ * This will not invoke `shouldUpdateComponent`, but it will invoke
+ * `componentWillUpdate` and `componentDidUpdate`.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @internal
+ */
+ enqueueForceUpdate: function(publicInstance) {
+ var internalInstance = getInternalInstanceReadyForUpdate(
+ publicInstance,
+ 'forceUpdate'
+ );
+
+ if (!internalInstance) {
+ return;
+ }
+
+ internalInstance._pendingForceUpdate = true;
+
+ enqueueUpdate(internalInstance);
+ },
+
+ /**
+ * Replaces all of the state. Always use this or `setState` to mutate state.
+ * You should treat `this.state` as immutable.
+ *
+ * There is no guarantee that `this.state` will be immediately updated, so
+ * accessing `this.state` after calling this method may return the old value.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} completeState Next state.
+ * @internal
+ */
+ enqueueReplaceState: function(publicInstance, completeState) {
+ var internalInstance = getInternalInstanceReadyForUpdate(
+ publicInstance,
+ 'replaceState'
+ );
+
+ if (!internalInstance) {
+ return;
+ }
+
+ internalInstance._pendingStateQueue = [completeState];
+ internalInstance._pendingReplaceState = true;
+
+ enqueueUpdate(internalInstance);
+ },
+
+ /**
+ * Sets a subset of the state. This only exists because _pendingState is
+ * internal. This provides a merging strategy that is not available to deep
+ * properties which is confusing. TODO: Expose pendingState or don't use it
+ * during the merge.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} partialState Next partial state to be merged with state.
+ * @internal
+ */
+ enqueueSetState: function(publicInstance, partialState) {
+ var internalInstance = getInternalInstanceReadyForUpdate(
+ publicInstance,
+ 'setState'
+ );
+
+ if (!internalInstance) {
+ return;
+ }
+
+ var queue =
+ internalInstance._pendingStateQueue ||
+ (internalInstance._pendingStateQueue = []);
+ queue.push(partialState);
+
+ enqueueUpdate(internalInstance);
+ },
+
+ /**
+ * Sets a subset of the props.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} partialProps Subset of the next props.
+ * @internal
+ */
+ enqueueSetProps: function(publicInstance, partialProps) {
+ var internalInstance = getInternalInstanceReadyForUpdate(
+ publicInstance,
+ 'setProps'
+ );
+
+ if (!internalInstance) {
+ return;
+ }
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ internalInstance._isTopLevel,
+ 'setProps(...): You called `setProps` on a ' +
+ 'component with a parent. This is an anti-pattern since props will ' +
+ 'get reactively updated when rendered. Instead, change the owner\'s ' +
+ '`render` method to pass the correct value as props to the component ' +
+ 'where it is created.'
+ ) : invariant(internalInstance._isTopLevel));
+
+ // Merge with the pending element if it exists, otherwise with existing
+ // element props.
+ var element = internalInstance._pendingElement ||
+ internalInstance._currentElement;
+ var props = assign({}, element.props, partialProps);
+ internalInstance._pendingElement = ReactElement.cloneAndReplaceProps(
+ element,
+ props
+ );
+
+ enqueueUpdate(internalInstance);
+ },
+
+ /**
+ * Replaces all of the props.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} props New props.
+ * @internal
+ */
+ enqueueReplaceProps: function(publicInstance, props) {
+ var internalInstance = getInternalInstanceReadyForUpdate(
+ publicInstance,
+ 'replaceProps'
+ );
+
+ if (!internalInstance) {
+ return;
+ }
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ internalInstance._isTopLevel,
+ 'replaceProps(...): You called `replaceProps` on a ' +
+ 'component with a parent. This is an anti-pattern since props will ' +
+ 'get reactively updated when rendered. Instead, change the owner\'s ' +
+ '`render` method to pass the correct value as props to the component ' +
+ 'where it is created.'
+ ) : invariant(internalInstance._isTopLevel));
+
+ // Merge with the pending element if it exists, otherwise with existing
+ // element props.
+ var element = internalInstance._pendingElement ||
+ internalInstance._currentElement;
+ internalInstance._pendingElement = ReactElement.cloneAndReplaceProps(
+ element,
+ props
+ );
+
+ enqueueUpdate(internalInstance);
+ },
+
+ enqueueElementInternal: function(internalInstance, newElement) {
+ internalInstance._pendingElement = newElement;
+ enqueueUpdate(internalInstance);
+ }
+
+ };
+
+ module.exports = ReactUpdateQueue;
+
+
+/***/ },
+/* 75 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactUpdates
+ */
+
+ 'use strict';
+
+ var CallbackQueue = __webpack_require__(76);
+ var PooledClass = __webpack_require__(60);
+ var ReactCurrentOwner = __webpack_require__(68);
+ var ReactPerf = __webpack_require__(77);
+ var ReactReconciler = __webpack_require__(78);
+ var Transaction = __webpack_require__(85);
+
+ var assign = __webpack_require__(64);
+ var invariant = __webpack_require__(58);
+ var warning = __webpack_require__(66);
+
+ var dirtyComponents = [];
+ var asapCallbackQueue = CallbackQueue.getPooled();
+ var asapEnqueued = false;
+
+ var batchingStrategy = null;
+
+ function ensureInjected() {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ ReactUpdates.ReactReconcileTransaction && batchingStrategy,
+ 'ReactUpdates: must inject a reconcile transaction class and batching ' +
+ 'strategy'
+ ) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy));
+ }
+
+ var NESTED_UPDATES = {
+ initialize: function() {
+ this.dirtyComponentsLength = dirtyComponents.length;
+ },
+ close: function() {
+ if (this.dirtyComponentsLength !== dirtyComponents.length) {
+ // Additional updates were enqueued by componentDidUpdate handlers or
+ // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
+ // these new updates so that if A's componentDidUpdate calls setState on
+ // B, B will update before the callback A's updater provided when calling
+ // setState.
+ dirtyComponents.splice(0, this.dirtyComponentsLength);
+ flushBatchedUpdates();
+ } else {
+ dirtyComponents.length = 0;
+ }
+ }
+ };
+
+ var UPDATE_QUEUEING = {
+ initialize: function() {
+ this.callbackQueue.reset();
+ },
+ close: function() {
+ this.callbackQueue.notifyAll();
+ }
+ };
+
+ var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
+
+ function ReactUpdatesFlushTransaction() {
+ this.reinitializeTransaction();
+ this.dirtyComponentsLength = null;
+ this.callbackQueue = CallbackQueue.getPooled();
+ this.reconcileTransaction =
+ ReactUpdates.ReactReconcileTransaction.getPooled();
+ }
+
+ assign(
+ ReactUpdatesFlushTransaction.prototype,
+ Transaction.Mixin, {
+ getTransactionWrappers: function() {
+ return TRANSACTION_WRAPPERS;
+ },
+
+ destructor: function() {
+ this.dirtyComponentsLength = null;
+ CallbackQueue.release(this.callbackQueue);
+ this.callbackQueue = null;
+ ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
+ this.reconcileTransaction = null;
+ },
+
+ perform: function(method, scope, a) {
+ // Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
+ // with this transaction's wrappers around it.
+ return Transaction.Mixin.perform.call(
+ this,
+ this.reconcileTransaction.perform,
+ this.reconcileTransaction,
+ method,
+ scope,
+ a
+ );
+ }
+ });
+
+ PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
+
+ function batchedUpdates(callback, a, b, c, d) {
+ ensureInjected();
+ batchingStrategy.batchedUpdates(callback, a, b, c, d);
+ }
+
+ /**
+ * Array comparator for ReactComponents by mount ordering.
+ *
+ * @param {ReactComponent} c1 first component you're comparing
+ * @param {ReactComponent} c2 second component you're comparing
+ * @return {number} Return value usable by Array.prototype.sort().
+ */
+ function mountOrderComparator(c1, c2) {
+ return c1._mountOrder - c2._mountOrder;
+ }
+
+ function runBatchedUpdates(transaction) {
+ var len = transaction.dirtyComponentsLength;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ len === dirtyComponents.length,
+ 'Expected flush transaction\'s stored dirty-components length (%s) to ' +
+ 'match dirty-components array length (%s).',
+ len,
+ dirtyComponents.length
+ ) : invariant(len === dirtyComponents.length));
+
+ // Since reconciling a component higher in the owner hierarchy usually (not
+ // always -- see shouldComponentUpdate()) will reconcile children, reconcile
+ // them before their children by sorting the array.
+ dirtyComponents.sort(mountOrderComparator);
+
+ for (var i = 0; i < len; i++) {
+ // If a component is unmounted before pending changes apply, it will still
+ // be here, but we assume that it has cleared its _pendingCallbacks and
+ // that performUpdateIfNecessary is a noop.
+ var component = dirtyComponents[i];
+
+ // If performUpdateIfNecessary happens to enqueue any new updates, we
+ // shouldn't execute the callbacks until the next render happens, so
+ // stash the callbacks first
+ var callbacks = component._pendingCallbacks;
+ component._pendingCallbacks = null;
+
+ ReactReconciler.performUpdateIfNecessary(
+ component,
+ transaction.reconcileTransaction
+ );
+
+ if (callbacks) {
+ for (var j = 0; j < callbacks.length; j++) {
+ transaction.callbackQueue.enqueue(
+ callbacks[j],
+ component.getPublicInstance()
+ );
+ }
+ }
+ }
+ }
+
+ var flushBatchedUpdates = function() {
+ // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
+ // array and perform any updates enqueued by mount-ready handlers (i.e.,
+ // componentDidUpdate) but we need to check here too in order to catch
+ // updates enqueued by setState callbacks and asap calls.
+ while (dirtyComponents.length || asapEnqueued) {
+ if (dirtyComponents.length) {
+ var transaction = ReactUpdatesFlushTransaction.getPooled();
+ transaction.perform(runBatchedUpdates, null, transaction);
+ ReactUpdatesFlushTransaction.release(transaction);
+ }
+
+ if (asapEnqueued) {
+ asapEnqueued = false;
+ var queue = asapCallbackQueue;
+ asapCallbackQueue = CallbackQueue.getPooled();
+ queue.notifyAll();
+ CallbackQueue.release(queue);
+ }
+ }
+ };
+ flushBatchedUpdates = ReactPerf.measure(
+ 'ReactUpdates',
+ 'flushBatchedUpdates',
+ flushBatchedUpdates
+ );
+
+ /**
+ * Mark a component as needing a rerender, adding an optional callback to a
+ * list of functions which will be executed once the rerender occurs.
+ */
+ function enqueueUpdate(component) {
+ ensureInjected();
+
+ // Various parts of our code (such as ReactCompositeComponent's
+ // _renderValidatedComponent) assume that calls to render aren't nested;
+ // verify that that's the case. (This is called by each top-level update
+ // function, like setProps, setState, forceUpdate, etc.; creation and
+ // destruction of top-level components is guarded in ReactMount.)
+ ("production" !== process.env.NODE_ENV ? warning(
+ ReactCurrentOwner.current == null,
+ 'enqueueUpdate(): Render methods should be a pure function of props ' +
+ 'and state; triggering nested component updates from render is not ' +
+ 'allowed. If necessary, trigger nested updates in ' +
+ 'componentDidUpdate.'
+ ) : null);
+
+ if (!batchingStrategy.isBatchingUpdates) {
+ batchingStrategy.batchedUpdates(enqueueUpdate, component);
+ return;
+ }
+
+ dirtyComponents.push(component);
+ }
+
+ /**
+ * Enqueue a callback to be run at the end of the current batching cycle. Throws
+ * if no updates are currently being performed.
+ */
+ function asap(callback, context) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ batchingStrategy.isBatchingUpdates,
+ 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' +
+ 'updates are not being batched.'
+ ) : invariant(batchingStrategy.isBatchingUpdates));
+ asapCallbackQueue.enqueue(callback, context);
+ asapEnqueued = true;
+ }
+
+ var ReactUpdatesInjection = {
+ injectReconcileTransaction: function(ReconcileTransaction) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ ReconcileTransaction,
+ 'ReactUpdates: must provide a reconcile transaction class'
+ ) : invariant(ReconcileTransaction));
+ ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
+ },
+
+ injectBatchingStrategy: function(_batchingStrategy) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ _batchingStrategy,
+ 'ReactUpdates: must provide a batching strategy'
+ ) : invariant(_batchingStrategy));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof _batchingStrategy.batchedUpdates === 'function',
+ 'ReactUpdates: must provide a batchedUpdates() function'
+ ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function'));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof _batchingStrategy.isBatchingUpdates === 'boolean',
+ 'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
+ ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean'));
+ batchingStrategy = _batchingStrategy;
+ }
+ };
+
+ var ReactUpdates = {
+ /**
+ * React references `ReactReconcileTransaction` using this property in order
+ * to allow dependency injection.
+ *
+ * @internal
+ */
+ ReactReconcileTransaction: null,
+
+ batchedUpdates: batchedUpdates,
+ enqueueUpdate: enqueueUpdate,
+ flushBatchedUpdates: flushBatchedUpdates,
+ injection: ReactUpdatesInjection,
+ asap: asap
+ };
+
+ module.exports = ReactUpdates;
+
+
+/***/ },
+/* 76 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule CallbackQueue
+ */
+
+ 'use strict';
+
+ var PooledClass = __webpack_require__(60);
+
+ var assign = __webpack_require__(64);
+ var invariant = __webpack_require__(58);
+
+ /**
+ * A specialized pseudo-event module to help keep track of components waiting to
+ * be notified when their DOM representations are available for use.
+ *
+ * This implements `PooledClass`, so you should never need to instantiate this.
+ * Instead, use `CallbackQueue.getPooled()`.
+ *
+ * @class ReactMountReady
+ * @implements PooledClass
+ * @internal
+ */
+ function CallbackQueue() {
+ this._callbacks = null;
+ this._contexts = null;
+ }
+
+ assign(CallbackQueue.prototype, {
+
+ /**
+ * Enqueues a callback to be invoked when `notifyAll` is invoked.
+ *
+ * @param {function} callback Invoked when `notifyAll` is invoked.
+ * @param {?object} context Context to call `callback` with.
+ * @internal
+ */
+ enqueue: function(callback, context) {
+ this._callbacks = this._callbacks || [];
+ this._contexts = this._contexts || [];
+ this._callbacks.push(callback);
+ this._contexts.push(context);
+ },
+
+ /**
+ * Invokes all enqueued callbacks and clears the queue. This is invoked after
+ * the DOM representation of a component has been created or updated.
+ *
+ * @internal
+ */
+ notifyAll: function() {
+ var callbacks = this._callbacks;
+ var contexts = this._contexts;
+ if (callbacks) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ callbacks.length === contexts.length,
+ 'Mismatched list of contexts in callback queue'
+ ) : invariant(callbacks.length === contexts.length));
+ this._callbacks = null;
+ this._contexts = null;
+ for (var i = 0, l = callbacks.length; i < l; i++) {
+ callbacks[i].call(contexts[i]);
+ }
+ callbacks.length = 0;
+ contexts.length = 0;
+ }
+ },
+
+ /**
+ * Resets the internal queue.
+ *
+ * @internal
+ */
+ reset: function() {
+ this._callbacks = null;
+ this._contexts = null;
+ },
+
+ /**
+ * `PooledClass` looks for this.
+ */
+ destructor: function() {
+ this.reset();
+ }
+
+ });
+
+ PooledClass.addPoolingTo(CallbackQueue);
+
+ module.exports = CallbackQueue;
+
+
+/***/ },
+/* 77 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactPerf
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ /**
+ * ReactPerf is a general AOP system designed to measure performance. This
+ * module only has the hooks: see ReactDefaultPerf for the analysis tool.
+ */
+ var ReactPerf = {
+ /**
+ * Boolean to enable/disable measurement. Set to false by default to prevent
+ * accidental logging and perf loss.
+ */
+ enableMeasure: false,
+
+ /**
+ * Holds onto the measure function in use. By default, don't measure
+ * anything, but we'll override this if we inject a measure function.
+ */
+ storedMeasure: _noMeasure,
+
+ /**
+ * @param {object} object
+ * @param {string} objectName
+ * @param {object} methodNames
+ */
+ measureMethods: function(object, objectName, methodNames) {
+ if ("production" !== process.env.NODE_ENV) {
+ for (var key in methodNames) {
+ if (!methodNames.hasOwnProperty(key)) {
+ continue;
+ }
+ object[key] = ReactPerf.measure(
+ objectName,
+ methodNames[key],
+ object[key]
+ );
+ }
+ }
+ },
+
+ /**
+ * Use this to wrap methods you want to measure. Zero overhead in production.
+ *
+ * @param {string} objName
+ * @param {string} fnName
+ * @param {function} func
+ * @return {function}
+ */
+ measure: function(objName, fnName, func) {
+ if ("production" !== process.env.NODE_ENV) {
+ var measuredFunc = null;
+ var wrapper = function() {
+ if (ReactPerf.enableMeasure) {
+ if (!measuredFunc) {
+ measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
+ }
+ return measuredFunc.apply(this, arguments);
+ }
+ return func.apply(this, arguments);
+ };
+ wrapper.displayName = objName + '_' + fnName;
+ return wrapper;
+ }
+ return func;
+ },
+
+ injection: {
+ /**
+ * @param {function} measure
+ */
+ injectMeasure: function(measure) {
+ ReactPerf.storedMeasure = measure;
+ }
+ }
+ };
+
+ /**
+ * Simply passes through the measured function, without measuring it.
+ *
+ * @param {string} objName
+ * @param {string} fnName
+ * @param {function} func
+ * @return {function}
+ */
+ function _noMeasure(objName, fnName, func) {
+ return func;
+ }
+
+ module.exports = ReactPerf;
+
+
+/***/ },
+/* 78 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactReconciler
+ */
+
+ 'use strict';
+
+ var ReactRef = __webpack_require__(79);
+ var ReactElementValidator = __webpack_require__(81);
+
+ /**
+ * Helper to call ReactRef.attachRefs with this composite component, split out
+ * to avoid allocations in the transaction mount-ready queue.
+ */
+ function attachRefs() {
+ ReactRef.attachRefs(this, this._currentElement);
+ }
+
+ var ReactReconciler = {
+
+ /**
+ * Initializes the component, renders markup, and registers event listeners.
+ *
+ * @param {ReactComponent} internalInstance
+ * @param {string} rootID DOM ID of the root node.
+ * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
+ * @return {?string} Rendered markup to be inserted into the DOM.
+ * @final
+ * @internal
+ */
+ mountComponent: function(internalInstance, rootID, transaction, context) {
+ var markup = internalInstance.mountComponent(rootID, transaction, context);
+ if ("production" !== process.env.NODE_ENV) {
+ ReactElementValidator.checkAndWarnForMutatedProps(
+ internalInstance._currentElement
+ );
+ }
+ transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
+ return markup;
+ },
+
+ /**
+ * Releases any resources allocated by `mountComponent`.
+ *
+ * @final
+ * @internal
+ */
+ unmountComponent: function(internalInstance) {
+ ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
+ internalInstance.unmountComponent();
+ },
+
+ /**
+ * Update a component using a new element.
+ *
+ * @param {ReactComponent} internalInstance
+ * @param {ReactElement} nextElement
+ * @param {ReactReconcileTransaction} transaction
+ * @param {object} context
+ * @internal
+ */
+ receiveComponent: function(
+ internalInstance, nextElement, transaction, context
+ ) {
+ var prevElement = internalInstance._currentElement;
+
+ if (nextElement === prevElement && nextElement._owner != null) {
+ // Since elements are immutable after the owner is rendered,
+ // we can do a cheap identity compare here to determine if this is a
+ // superfluous reconcile. It's possible for state to be mutable but such
+ // change should trigger an update of the owner which would recreate
+ // the element. We explicitly check for the existence of an owner since
+ // it's possible for an element created outside a composite to be
+ // deeply mutated and reused.
+ return;
+ }
+
+ if ("production" !== process.env.NODE_ENV) {
+ ReactElementValidator.checkAndWarnForMutatedProps(nextElement);
+ }
+
+ var refsChanged = ReactRef.shouldUpdateRefs(
+ prevElement,
+ nextElement
+ );
+
+ if (refsChanged) {
+ ReactRef.detachRefs(internalInstance, prevElement);
+ }
+
+ internalInstance.receiveComponent(nextElement, transaction, context);
+
+ if (refsChanged) {
+ transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
+ }
+ },
+
+ /**
+ * Flush any dirty changes in a component.
+ *
+ * @param {ReactComponent} internalInstance
+ * @param {ReactReconcileTransaction} transaction
+ * @internal
+ */
+ performUpdateIfNecessary: function(
+ internalInstance,
+ transaction
+ ) {
+ internalInstance.performUpdateIfNecessary(transaction);
+ }
+
+ };
+
+ module.exports = ReactReconciler;
+
+
+/***/ },
+/* 79 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactRef
+ */
+
+ 'use strict';
+
+ var ReactOwner = __webpack_require__(80);
+
+ var ReactRef = {};
+
+ function attachRef(ref, component, owner) {
+ if (typeof ref === 'function') {
+ ref(component.getPublicInstance());
+ } else {
+ // Legacy ref
+ ReactOwner.addComponentAsRefTo(component, ref, owner);
+ }
+ }
+
+ function detachRef(ref, component, owner) {
+ if (typeof ref === 'function') {
+ ref(null);
+ } else {
+ // Legacy ref
+ ReactOwner.removeComponentAsRefFrom(component, ref, owner);
+ }
+ }
+
+ ReactRef.attachRefs = function(instance, element) {
+ var ref = element.ref;
+ if (ref != null) {
+ attachRef(ref, instance, element._owner);
+ }
+ };
+
+ ReactRef.shouldUpdateRefs = function(prevElement, nextElement) {
+ // If either the owner or a `ref` has changed, make sure the newest owner
+ // has stored a reference to `this`, and the previous owner (if different)
+ // has forgotten the reference to `this`. We use the element instead
+ // of the public this.props because the post processing cannot determine
+ // a ref. The ref conceptually lives on the element.
+
+ // TODO: Should this even be possible? The owner cannot change because
+ // it's forbidden by shouldUpdateReactComponent. The ref can change
+ // if you swap the keys of but not the refs. Reconsider where this check
+ // is made. It probably belongs where the key checking and
+ // instantiateReactComponent is done.
+
+ return (
+ nextElement._owner !== prevElement._owner ||
+ nextElement.ref !== prevElement.ref
+ );
+ };
+
+ ReactRef.detachRefs = function(instance, element) {
+ var ref = element.ref;
+ if (ref != null) {
+ detachRef(ref, instance, element._owner);
+ }
+ };
+
+ module.exports = ReactRef;
+
+
+/***/ },
+/* 80 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactOwner
+ */
+
+ 'use strict';
+
+ var invariant = __webpack_require__(58);
+
+ /**
+ * ReactOwners are capable of storing references to owned components.
+ *
+ * All components are capable of //being// referenced by owner components, but
+ * only ReactOwner components are capable of //referencing// owned components.
+ * The named reference is known as a "ref".
+ *
+ * Refs are available when mounted and updated during reconciliation.
+ *
+ * var MyComponent = React.createClass({
+ * render: function() {
+ * return (
+ *
+ *
+ *
+ * );
+ * },
+ * handleClick: function() {
+ * this.refs.custom.handleClick();
+ * },
+ * componentDidMount: function() {
+ * this.refs.custom.initialize();
+ * }
+ * });
+ *
+ * Refs should rarely be used. When refs are used, they should only be done to
+ * control data that is not handled by React's data flow.
+ *
+ * @class ReactOwner
+ */
+ var ReactOwner = {
+
+ /**
+ * @param {?object} object
+ * @return {boolean} True if `object` is a valid owner.
+ * @final
+ */
+ isValidOwner: function(object) {
+ return !!(
+ (object &&
+ typeof object.attachRef === 'function' && typeof object.detachRef === 'function')
+ );
+ },
+
+ /**
+ * Adds a component by ref to an owner component.
+ *
+ * @param {ReactComponent} component Component to reference.
+ * @param {string} ref Name by which to refer to the component.
+ * @param {ReactOwner} owner Component on which to record the ref.
+ * @final
+ * @internal
+ */
+ addComponentAsRefTo: function(component, ref, owner) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ ReactOwner.isValidOwner(owner),
+ 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' +
+ 'usually means that you\'re trying to add a ref to a component that ' +
+ 'doesn\'t have an owner (that is, was not created inside of another ' +
+ 'component\'s `render` method). Try rendering this component inside of ' +
+ 'a new top-level component which will hold the ref.'
+ ) : invariant(ReactOwner.isValidOwner(owner)));
+ owner.attachRef(ref, component);
+ },
+
+ /**
+ * Removes a component by ref from an owner component.
+ *
+ * @param {ReactComponent} component Component to dereference.
+ * @param {string} ref Name of the ref to remove.
+ * @param {ReactOwner} owner Component on which the ref is recorded.
+ * @final
+ * @internal
+ */
+ removeComponentAsRefFrom: function(component, ref, owner) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ ReactOwner.isValidOwner(owner),
+ 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
+ 'usually means that you\'re trying to remove a ref to a component that ' +
+ 'doesn\'t have an owner (that is, was not created inside of another ' +
+ 'component\'s `render` method). Try rendering this component inside of ' +
+ 'a new top-level component which will hold the ref.'
+ ) : invariant(ReactOwner.isValidOwner(owner)));
+ // Check that `component` is still the current ref because we do not want to
+ // detach the ref if another component stole it.
+ if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
+ owner.detachRef(ref);
+ }
+ }
+
+ };
+
+ module.exports = ReactOwner;
+
+
+/***/ },
+/* 81 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactElementValidator
+ */
+
+ /**
+ * ReactElementValidator provides a wrapper around a element factory
+ * which validates the props passed to the element. This is intended to be
+ * used only in DEV and could be replaced by a static type checker for languages
+ * that support it.
+ */
+
+ 'use strict';
+
+ var ReactElement = __webpack_require__(62);
+ var ReactFragment = __webpack_require__(61);
+ var ReactPropTypeLocations = __webpack_require__(82);
+ var ReactPropTypeLocationNames = __webpack_require__(83);
+ var ReactCurrentOwner = __webpack_require__(68);
+ var ReactNativeComponent = __webpack_require__(84);
+
+ var getIteratorFn = __webpack_require__(70);
+ var invariant = __webpack_require__(58);
+ var warning = __webpack_require__(66);
+
+ function getDeclarationErrorAddendum() {
+ if (ReactCurrentOwner.current) {
+ var name = ReactCurrentOwner.current.getName();
+ if (name) {
+ return ' Check the render method of `' + name + '`.';
+ }
+ }
+ return '';
+ }
+
+ /**
+ * Warn if there's no key explicitly set on dynamic arrays of children or
+ * object keys are not valid. This allows us to keep track of children between
+ * updates.
+ */
+ var ownerHasKeyUseWarning = {};
+
+ var loggedTypeFailures = {};
+
+ var NUMERIC_PROPERTY_REGEX = /^\d+$/;
+
+ /**
+ * Gets the instance's name for use in warnings.
+ *
+ * @internal
+ * @return {?string} Display name or undefined
+ */
+ function getName(instance) {
+ var publicInstance = instance && instance.getPublicInstance();
+ if (!publicInstance) {
+ return undefined;
+ }
+ var constructor = publicInstance.constructor;
+ if (!constructor) {
+ return undefined;
+ }
+ return constructor.displayName || constructor.name || undefined;
+ }
+
+ /**
+ * Gets the current owner's displayName for use in warnings.
+ *
+ * @internal
+ * @return {?string} Display name or undefined
+ */
+ function getCurrentOwnerDisplayName() {
+ var current = ReactCurrentOwner.current;
+ return (
+ current && getName(current) || undefined
+ );
+ }
+
+ /**
+ * Warn if the element doesn't have an explicit key assigned to it.
+ * This element is in an array. The array could grow and shrink or be
+ * reordered. All children that haven't already been validated are required to
+ * have a "key" property assigned to it.
+ *
+ * @internal
+ * @param {ReactElement} element Element that requires a key.
+ * @param {*} parentType element's parent's type.
+ */
+ function validateExplicitKey(element, parentType) {
+ if (element._store.validated || element.key != null) {
+ return;
+ }
+ element._store.validated = true;
+
+ warnAndMonitorForKeyUse(
+ 'Each child in an array or iterator should have a unique "key" prop.',
+ element,
+ parentType
+ );
+ }
+
+ /**
+ * Warn if the key is being defined as an object property but has an incorrect
+ * value.
+ *
+ * @internal
+ * @param {string} name Property name of the key.
+ * @param {ReactElement} element Component that requires a key.
+ * @param {*} parentType element's parent's type.
+ */
+ function validatePropertyKey(name, element, parentType) {
+ if (!NUMERIC_PROPERTY_REGEX.test(name)) {
+ return;
+ }
+ warnAndMonitorForKeyUse(
+ 'Child objects should have non-numeric keys so ordering is preserved.',
+ element,
+ parentType
+ );
+ }
+
+ /**
+ * Shared warning and monitoring code for the key warnings.
+ *
+ * @internal
+ * @param {string} message The base warning that gets output.
+ * @param {ReactElement} element Component that requires a key.
+ * @param {*} parentType element's parent's type.
+ */
+ function warnAndMonitorForKeyUse(message, element, parentType) {
+ var ownerName = getCurrentOwnerDisplayName();
+ var parentName = typeof parentType === 'string' ?
+ parentType : parentType.displayName || parentType.name;
+
+ var useName = ownerName || parentName;
+ var memoizer = ownerHasKeyUseWarning[message] || (
+ (ownerHasKeyUseWarning[message] = {})
+ );
+ if (memoizer.hasOwnProperty(useName)) {
+ return;
+ }
+ memoizer[useName] = true;
+
+ var parentOrOwnerAddendum =
+ ownerName ? (" Check the render method of " + ownerName + ".") :
+ parentName ? (" Check the React.render call using <" + parentName + ">.") :
+ '';
+
+ // Usually the current owner is the offender, but if it accepts children as a
+ // property, it may be the creator of the child that's responsible for
+ // assigning it a key.
+ var childOwnerAddendum = '';
+ if (element &&
+ element._owner &&
+ element._owner !== ReactCurrentOwner.current) {
+ // Name of the component that originally created this child.
+ var childOwnerName = getName(element._owner);
+
+ childOwnerAddendum = (" It was passed a child from " + childOwnerName + ".");
+ }
+
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ message + '%s%s See https://fb.me/react-warning-keys for more information.',
+ parentOrOwnerAddendum,
+ childOwnerAddendum
+ ) : null);
+ }
+
+ /**
+ * Ensure that every element either is passed in a static location, in an
+ * array with an explicit keys property defined, or in an object literal
+ * with valid key property.
+ *
+ * @internal
+ * @param {ReactNode} node Statically passed child of any type.
+ * @param {*} parentType node's parent's type.
+ */
+ function validateChildKeys(node, parentType) {
+ if (Array.isArray(node)) {
+ for (var i = 0; i < node.length; i++) {
+ var child = node[i];
+ if (ReactElement.isValidElement(child)) {
+ validateExplicitKey(child, parentType);
+ }
+ }
+ } else if (ReactElement.isValidElement(node)) {
+ // This element was passed in a valid location.
+ node._store.validated = true;
+ } else if (node) {
+ var iteratorFn = getIteratorFn(node);
+ // Entry iterators provide implicit keys.
+ if (iteratorFn) {
+ if (iteratorFn !== node.entries) {
+ var iterator = iteratorFn.call(node);
+ var step;
+ while (!(step = iterator.next()).done) {
+ if (ReactElement.isValidElement(step.value)) {
+ validateExplicitKey(step.value, parentType);
+ }
+ }
+ }
+ } else if (typeof node === 'object') {
+ var fragment = ReactFragment.extractIfFragment(node);
+ for (var key in fragment) {
+ if (fragment.hasOwnProperty(key)) {
+ validatePropertyKey(key, fragment[key], parentType);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Assert that the props are valid
+ *
+ * @param {string} componentName Name of the component for error messages.
+ * @param {object} propTypes Map of prop name to a ReactPropType
+ * @param {object} props
+ * @param {string} location e.g. "prop", "context", "child context"
+ * @private
+ */
+ function checkPropTypes(componentName, propTypes, props, location) {
+ for (var propName in propTypes) {
+ if (propTypes.hasOwnProperty(propName)) {
+ var error;
+ // Prop type validation may throw. In case they do, we don't want to
+ // fail the render phase where it didn't fail before. So we log it.
+ // After these have been cleaned up, we'll let them throw.
+ try {
+ // This is intentionally an invariant that gets caught. It's the same
+ // behavior as without this statement except with a better message.
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof propTypes[propName] === 'function',
+ '%s: %s type `%s` is invalid; it must be a function, usually from ' +
+ 'React.PropTypes.',
+ componentName || 'React class',
+ ReactPropTypeLocationNames[location],
+ propName
+ ) : invariant(typeof propTypes[propName] === 'function'));
+ error = propTypes[propName](props, propName, componentName, location);
+ } catch (ex) {
+ error = ex;
+ }
+ if (error instanceof Error && !(error.message in loggedTypeFailures)) {
+ // Only monitor this failure once because there tends to be a lot of the
+ // same error.
+ loggedTypeFailures[error.message] = true;
+
+ var addendum = getDeclarationErrorAddendum(this);
+ ("production" !== process.env.NODE_ENV ? warning(false, 'Failed propType: %s%s', error.message, addendum) : null);
+ }
+ }
+ }
+ }
+
+ var warnedPropsMutations = {};
+
+ /**
+ * Warn about mutating props when setting `propName` on `element`.
+ *
+ * @param {string} propName The string key within props that was set
+ * @param {ReactElement} element
+ */
+ function warnForPropsMutation(propName, element) {
+ var type = element.type;
+ var elementName = typeof type === 'string' ? type : type.displayName;
+ var ownerName = element._owner ?
+ element._owner.getPublicInstance().constructor.displayName : null;
+
+ var warningKey = propName + '|' + elementName + '|' + ownerName;
+ if (warnedPropsMutations.hasOwnProperty(warningKey)) {
+ return;
+ }
+ warnedPropsMutations[warningKey] = true;
+
+ var elementInfo = '';
+ if (elementName) {
+ elementInfo = ' <' + elementName + ' />';
+ }
+ var ownerInfo = '';
+ if (ownerName) {
+ ownerInfo = ' The element was created by ' + ownerName + '.';
+ }
+
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'Don\'t set .props.%s of the React component%s. Instead, specify the ' +
+ 'correct value when initially creating the element or use ' +
+ 'React.cloneElement to make a new element with updated props.%s',
+ propName,
+ elementInfo,
+ ownerInfo
+ ) : null);
+ }
+
+ // Inline Object.is polyfill
+ function is(a, b) {
+ if (a !== a) {
+ // NaN
+ return b !== b;
+ }
+ if (a === 0 && b === 0) {
+ // +-0
+ return 1 / a === 1 / b;
+ }
+ return a === b;
+ }
+
+ /**
+ * Given an element, check if its props have been mutated since element
+ * creation (or the last call to this function). In particular, check if any
+ * new props have been added, which we can't directly catch by defining warning
+ * properties on the props object.
+ *
+ * @param {ReactElement} element
+ */
+ function checkAndWarnForMutatedProps(element) {
+ if (!element._store) {
+ // Element was created using `new ReactElement` directly or with
+ // `ReactElement.createElement`; skip mutation checking
+ return;
+ }
+
+ var originalProps = element._store.originalProps;
+ var props = element.props;
+
+ for (var propName in props) {
+ if (props.hasOwnProperty(propName)) {
+ if (!originalProps.hasOwnProperty(propName) ||
+ !is(originalProps[propName], props[propName])) {
+ warnForPropsMutation(propName, element);
+
+ // Copy over the new value so that the two props objects match again
+ originalProps[propName] = props[propName];
+ }
+ }
+ }
+ }
+
+ /**
+ * Given an element, validate that its props follow the propTypes definition,
+ * provided by the type.
+ *
+ * @param {ReactElement} element
+ */
+ function validatePropTypes(element) {
+ if (element.type == null) {
+ // This has already warned. Don't throw.
+ return;
+ }
+ // Extract the component class from the element. Converts string types
+ // to a composite class which may have propTypes.
+ // TODO: Validating a string's propTypes is not decoupled from the
+ // rendering target which is problematic.
+ var componentClass = ReactNativeComponent.getComponentClassForElement(
+ element
+ );
+ var name = componentClass.displayName || componentClass.name;
+ if (componentClass.propTypes) {
+ checkPropTypes(
+ name,
+ componentClass.propTypes,
+ element.props,
+ ReactPropTypeLocations.prop
+ );
+ }
+ if (typeof componentClass.getDefaultProps === 'function') {
+ ("production" !== process.env.NODE_ENV ? warning(
+ componentClass.getDefaultProps.isReactClassApproved,
+ 'getDefaultProps is only used on classic React.createClass ' +
+ 'definitions. Use a static property named `defaultProps` instead.'
+ ) : null);
+ }
+ }
+
+ var ReactElementValidator = {
+
+ checkAndWarnForMutatedProps: checkAndWarnForMutatedProps,
+
+ createElement: function(type, props, children) {
+ // We warn in this case but don't throw. We expect the element creation to
+ // succeed and there will likely be errors in render.
+ ("production" !== process.env.NODE_ENV ? warning(
+ type != null,
+ 'React.createElement: type should not be null or undefined. It should ' +
+ 'be a string (for DOM elements) or a ReactClass (for composite ' +
+ 'components).'
+ ) : null);
+
+ var element = ReactElement.createElement.apply(this, arguments);
+
+ // The result can be nullish if a mock or a custom function is used.
+ // TODO: Drop this when these are no longer allowed as the type argument.
+ if (element == null) {
+ return element;
+ }
+
+ for (var i = 2; i < arguments.length; i++) {
+ validateChildKeys(arguments[i], type);
+ }
+
+ validatePropTypes(element);
+
+ return element;
+ },
+
+ createFactory: function(type) {
+ var validatedFactory = ReactElementValidator.createElement.bind(
+ null,
+ type
+ );
+ // Legacy hook TODO: Warn if this is accessed
+ validatedFactory.type = type;
+
+ if ("production" !== process.env.NODE_ENV) {
+ try {
+ Object.defineProperty(
+ validatedFactory,
+ 'type',
+ {
+ enumerable: false,
+ get: function() {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'Factory.type is deprecated. Access the class directly ' +
+ 'before passing it to createFactory.'
+ ) : null);
+ Object.defineProperty(this, 'type', {
+ value: type
+ });
+ return type;
+ }
+ }
+ );
+ } catch (x) {
+ // IE will fail on defineProperty (es5-shim/sham too)
+ }
+ }
+
+
+ return validatedFactory;
+ },
+
+ cloneElement: function(element, props, children) {
+ var newElement = ReactElement.cloneElement.apply(this, arguments);
+ for (var i = 2; i < arguments.length; i++) {
+ validateChildKeys(arguments[i], newElement.type);
+ }
+ validatePropTypes(newElement);
+ return newElement;
+ }
+
+ };
+
+ module.exports = ReactElementValidator;
+
+
+/***/ },
+/* 82 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactPropTypeLocations
+ */
+
+ 'use strict';
+
+ var keyMirror = __webpack_require__(57);
+
+ var ReactPropTypeLocations = keyMirror({
+ prop: null,
+ context: null,
+ childContext: null
+ });
+
+ module.exports = ReactPropTypeLocations;
+
+
+/***/ },
+/* 83 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactPropTypeLocationNames
+ */
+
+ 'use strict';
+
+ var ReactPropTypeLocationNames = {};
+
+ if ("production" !== process.env.NODE_ENV) {
+ ReactPropTypeLocationNames = {
+ prop: 'prop',
+ context: 'context',
+ childContext: 'child context'
+ };
+ }
+
+ module.exports = ReactPropTypeLocationNames;
+
+
+/***/ },
+/* 84 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2014-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactNativeComponent
+ */
+
+ 'use strict';
+
+ var assign = __webpack_require__(64);
+ var invariant = __webpack_require__(58);
+
+ var autoGenerateWrapperClass = null;
+ var genericComponentClass = null;
+ // This registry keeps track of wrapper classes around native tags
+ var tagToComponentClass = {};
+ var textComponentClass = null;
+
+ var ReactNativeComponentInjection = {
+ // This accepts a class that receives the tag string. This is a catch all
+ // that can render any kind of tag.
+ injectGenericComponentClass: function(componentClass) {
+ genericComponentClass = componentClass;
+ },
+ // This accepts a text component class that takes the text string to be
+ // rendered as props.
+ injectTextComponentClass: function(componentClass) {
+ textComponentClass = componentClass;
+ },
+ // This accepts a keyed object with classes as values. Each key represents a
+ // tag. That particular tag will use this class instead of the generic one.
+ injectComponentClasses: function(componentClasses) {
+ assign(tagToComponentClass, componentClasses);
+ },
+ // Temporary hack since we expect DOM refs to behave like composites,
+ // for this release.
+ injectAutoWrapper: function(wrapperFactory) {
+ autoGenerateWrapperClass = wrapperFactory;
+ }
+ };
+
+ /**
+ * Get a composite component wrapper class for a specific tag.
+ *
+ * @param {ReactElement} element The tag for which to get the class.
+ * @return {function} The React class constructor function.
+ */
+ function getComponentClassForElement(element) {
+ if (typeof element.type === 'function') {
+ return element.type;
+ }
+ var tag = element.type;
+ var componentClass = tagToComponentClass[tag];
+ if (componentClass == null) {
+ tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
+ }
+ return componentClass;
+ }
+
+ /**
+ * Get a native internal component class for a specific tag.
+ *
+ * @param {ReactElement} element The element to create.
+ * @return {function} The internal class constructor function.
+ */
+ function createInternalComponent(element) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ genericComponentClass,
+ 'There is no registered component for the tag %s',
+ element.type
+ ) : invariant(genericComponentClass));
+ return new genericComponentClass(element.type, element.props);
+ }
+
+ /**
+ * @param {ReactText} text
+ * @return {ReactComponent}
+ */
+ function createInstanceForText(text) {
+ return new textComponentClass(text);
+ }
+
+ /**
+ * @param {ReactComponent} component
+ * @return {boolean}
+ */
+ function isTextComponent(component) {
+ return component instanceof textComponentClass;
+ }
+
+ var ReactNativeComponent = {
+ getComponentClassForElement: getComponentClassForElement,
+ createInternalComponent: createInternalComponent,
+ createInstanceForText: createInstanceForText,
+ isTextComponent: isTextComponent,
+ injection: ReactNativeComponentInjection
+ };
+
+ module.exports = ReactNativeComponent;
+
+
+/***/ },
+/* 85 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule Transaction
+ */
+
+ 'use strict';
+
+ var invariant = __webpack_require__(58);
+
+ /**
+ * `Transaction` creates a black box that is able to wrap any method such that
+ * certain invariants are maintained before and after the method is invoked
+ * (Even if an exception is thrown while invoking the wrapped method). Whoever
+ * instantiates a transaction can provide enforcers of the invariants at
+ * creation time. The `Transaction` class itself will supply one additional
+ * automatic invariant for you - the invariant that any transaction instance
+ * should not be run while it is already being run. You would typically create a
+ * single instance of a `Transaction` for reuse multiple times, that potentially
+ * is used to wrap several different methods. Wrappers are extremely simple -
+ * they only require implementing two methods.
+ *
+ *
+ *
+ * Use cases:
+ * - Preserving the input selection ranges before/after reconciliation.
+ * Restoring selection even in the event of an unexpected error.
+ * - Deactivating events while rearranging the DOM, preventing blurs/focuses,
+ * while guaranteeing that afterwards, the event system is reactivated.
+ * - Flushing a queue of collected DOM mutations to the main UI thread after a
+ * reconciliation takes place in a worker thread.
+ * - Invoking any collected `componentDidUpdate` callbacks after rendering new
+ * content.
+ * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
+ * to preserve the `scrollTop` (an automatic scroll aware DOM).
+ * - (Future use case): Layout calculations before and after DOM updates.
+ *
+ * Transactional plugin API:
+ * - A module that has an `initialize` method that returns any precomputation.
+ * - and a `close` method that accepts the precomputation. `close` is invoked
+ * when the wrapped process is completed, or has failed.
+ *
+ * @param {Array} transactionWrapper Wrapper modules
+ * that implement `initialize` and `close`.
+ * @return {Transaction} Single transaction for reuse in thread.
+ *
+ * @class Transaction
+ */
+ var Mixin = {
+ /**
+ * Sets up this instance so that it is prepared for collecting metrics. Does
+ * so such that this setup method may be used on an instance that is already
+ * initialized, in a way that does not consume additional memory upon reuse.
+ * That can be useful if you decide to make your subclass of this mixin a
+ * "PooledClass".
+ */
+ reinitializeTransaction: function() {
+ this.transactionWrappers = this.getTransactionWrappers();
+ if (!this.wrapperInitData) {
+ this.wrapperInitData = [];
+ } else {
+ this.wrapperInitData.length = 0;
+ }
+ this._isInTransaction = false;
+ },
+
+ _isInTransaction: false,
+
+ /**
+ * @abstract
+ * @return {Array} Array of transaction wrappers.
+ */
+ getTransactionWrappers: null,
+
+ isInTransaction: function() {
+ return !!this._isInTransaction;
+ },
+
+ /**
+ * Executes the function within a safety window. Use this for the top level
+ * methods that result in large amounts of computation/mutations that would
+ * need to be safety checked.
+ *
+ * @param {function} method Member of scope to call.
+ * @param {Object} scope Scope to invoke from.
+ * @param {Object?=} args... Arguments to pass to the method (optional).
+ * Helps prevent need to bind in many cases.
+ * @return Return value from `method`.
+ */
+ perform: function(method, scope, a, b, c, d, e, f) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !this.isInTransaction(),
+ 'Transaction.perform(...): Cannot initialize a transaction when there ' +
+ 'is already an outstanding transaction.'
+ ) : invariant(!this.isInTransaction()));
+ var errorThrown;
+ var ret;
+ try {
+ this._isInTransaction = true;
+ // Catching errors makes debugging more difficult, so we start with
+ // errorThrown set to true before setting it to false after calling
+ // close -- if it's still set to true in the finally block, it means
+ // one of these calls threw.
+ errorThrown = true;
+ this.initializeAll(0);
+ ret = method.call(scope, a, b, c, d, e, f);
+ errorThrown = false;
+ } finally {
+ try {
+ if (errorThrown) {
+ // If `method` throws, prefer to show that stack trace over any thrown
+ // by invoking `closeAll`.
+ try {
+ this.closeAll(0);
+ } catch (err) {
+ }
+ } else {
+ // Since `method` didn't throw, we don't want to silence the exception
+ // here.
+ this.closeAll(0);
+ }
+ } finally {
+ this._isInTransaction = false;
+ }
+ }
+ return ret;
+ },
+
+ initializeAll: function(startIndex) {
+ var transactionWrappers = this.transactionWrappers;
+ for (var i = startIndex; i < transactionWrappers.length; i++) {
+ var wrapper = transactionWrappers[i];
+ try {
+ // Catching errors makes debugging more difficult, so we start with the
+ // OBSERVED_ERROR state before overwriting it with the real return value
+ // of initialize -- if it's still set to OBSERVED_ERROR in the finally
+ // block, it means wrapper.initialize threw.
+ this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
+ this.wrapperInitData[i] = wrapper.initialize ?
+ wrapper.initialize.call(this) :
+ null;
+ } finally {
+ if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
+ // The initializer for wrapper i threw an error; initialize the
+ // remaining wrappers but silence any exceptions from them to ensure
+ // that the first error is the one to bubble up.
+ try {
+ this.initializeAll(i + 1);
+ } catch (err) {
+ }
+ }
+ }
+ }
+ },
+
+ /**
+ * Invokes each of `this.transactionWrappers.close[i]` functions, passing into
+ * them the respective return values of `this.transactionWrappers.init[i]`
+ * (`close`rs that correspond to initializers that failed will not be
+ * invoked).
+ */
+ closeAll: function(startIndex) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ this.isInTransaction(),
+ 'Transaction.closeAll(): Cannot close transaction when none are open.'
+ ) : invariant(this.isInTransaction()));
+ var transactionWrappers = this.transactionWrappers;
+ for (var i = startIndex; i < transactionWrappers.length; i++) {
+ var wrapper = transactionWrappers[i];
+ var initData = this.wrapperInitData[i];
+ var errorThrown;
+ try {
+ // Catching errors makes debugging more difficult, so we start with
+ // errorThrown set to true before setting it to false after calling
+ // close -- if it's still set to true in the finally block, it means
+ // wrapper.close threw.
+ errorThrown = true;
+ if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
+ wrapper.close.call(this, initData);
+ }
+ errorThrown = false;
+ } finally {
+ if (errorThrown) {
+ // The closer for wrapper i threw an error; close the remaining
+ // wrappers but silence any exceptions from them to ensure that the
+ // first error is the one to bubble up.
+ try {
+ this.closeAll(i + 1);
+ } catch (e) {
+ }
+ }
+ }
+ }
+ this.wrapperInitData.length = 0;
+ }
+ };
+
+ var Transaction = {
+
+ Mixin: Mixin,
+
+ /**
+ * Token to look for to determine if an error occured.
+ */
+ OBSERVED_ERROR: {}
+
+ };
+
+ module.exports = Transaction;
+
+
+/***/ },
+/* 86 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactLifeCycle
+ */
+
+ 'use strict';
+
+ /**
+ * This module manages the bookkeeping when a component is in the process
+ * of being mounted or being unmounted. This is used as a way to enforce
+ * invariants (or warnings) when it is not recommended to call
+ * setState/forceUpdate.
+ *
+ * currentlyMountingInstance: During the construction phase, it is not possible
+ * to trigger an update since the instance is not fully mounted yet. However, we
+ * currently allow this as a convenience for mutating the initial state.
+ *
+ * currentlyUnmountingInstance: During the unmounting phase, the instance is
+ * still mounted and can therefore schedule an update. However, this is not
+ * recommended and probably an error since it's about to be unmounted.
+ * Therefore we still want to trigger in an error for that case.
+ */
+
+ var ReactLifeCycle = {
+ currentlyMountingInstance: null,
+ currentlyUnmountingInstance: null
+ };
+
+ module.exports = ReactLifeCycle;
+
+
+/***/ },
+/* 87 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactInstanceMap
+ */
+
+ 'use strict';
+
+ /**
+ * `ReactInstanceMap` maintains a mapping from a public facing stateful
+ * instance (key) and the internal representation (value). This allows public
+ * methods to accept the user facing instance as an argument and map them back
+ * to internal methods.
+ */
+
+ // TODO: Replace this with ES6: var ReactInstanceMap = new Map();
+ var ReactInstanceMap = {
+
+ /**
+ * This API should be called `delete` but we'd have to make sure to always
+ * transform these to strings for IE support. When this transform is fully
+ * supported we can rename it.
+ */
+ remove: function(key) {
+ key._reactInternalInstance = undefined;
+ },
+
+ get: function(key) {
+ return key._reactInternalInstance;
+ },
+
+ has: function(key) {
+ return key._reactInternalInstance !== undefined;
+ },
+
+ set: function(key, value) {
+ key._reactInternalInstance = value;
+ }
+
+ };
+
+ module.exports = ReactInstanceMap;
+
+
+/***/ },
+/* 88 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactClass
+ */
+
+ 'use strict';
+
+ var ReactComponent = __webpack_require__(73);
+ var ReactCurrentOwner = __webpack_require__(68);
+ var ReactElement = __webpack_require__(62);
+ var ReactErrorUtils = __webpack_require__(89);
+ var ReactInstanceMap = __webpack_require__(87);
+ var ReactLifeCycle = __webpack_require__(86);
+ var ReactPropTypeLocations = __webpack_require__(82);
+ var ReactPropTypeLocationNames = __webpack_require__(83);
+ var ReactUpdateQueue = __webpack_require__(74);
+
+ var assign = __webpack_require__(64);
+ var invariant = __webpack_require__(58);
+ var keyMirror = __webpack_require__(57);
+ var keyOf = __webpack_require__(90);
+ var warning = __webpack_require__(66);
+
+ var MIXINS_KEY = keyOf({mixins: null});
+
+ /**
+ * Policies that describe methods in `ReactClassInterface`.
+ */
+ var SpecPolicy = keyMirror({
+ /**
+ * These methods may be defined only once by the class specification or mixin.
+ */
+ DEFINE_ONCE: null,
+ /**
+ * These methods may be defined by both the class specification and mixins.
+ * Subsequent definitions will be chained. These methods must return void.
+ */
+ DEFINE_MANY: null,
+ /**
+ * These methods are overriding the base class.
+ */
+ OVERRIDE_BASE: null,
+ /**
+ * These methods are similar to DEFINE_MANY, except we assume they return
+ * objects. We try to merge the keys of the return values of all the mixed in
+ * functions. If there is a key conflict we throw.
+ */
+ DEFINE_MANY_MERGED: null
+ });
+
+
+ var injectedMixins = [];
+
+ /**
+ * Composite components are higher-level components that compose other composite
+ * or native components.
+ *
+ * To create a new type of `ReactClass`, pass a specification of
+ * your new class to `React.createClass`. The only requirement of your class
+ * specification is that you implement a `render` method.
+ *
+ * var MyComponent = React.createClass({
+ * render: function() {
+ * return
Hello World
;
+ * }
+ * });
+ *
+ * The class specification supports a specific protocol of methods that have
+ * special meaning (e.g. `render`). See `ReactClassInterface` for
+ * more the comprehensive protocol. Any other properties and methods in the
+ * class specification will available on the prototype.
+ *
+ * @interface ReactClassInterface
+ * @internal
+ */
+ var ReactClassInterface = {
+
+ /**
+ * An array of Mixin objects to include when defining your component.
+ *
+ * @type {array}
+ * @optional
+ */
+ mixins: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * An object containing properties and methods that should be defined on
+ * the component's constructor instead of its prototype (static methods).
+ *
+ * @type {object}
+ * @optional
+ */
+ statics: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Definition of prop types for this component.
+ *
+ * @type {object}
+ * @optional
+ */
+ propTypes: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Definition of context types for this component.
+ *
+ * @type {object}
+ * @optional
+ */
+ contextTypes: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Definition of context types this component sets for its children.
+ *
+ * @type {object}
+ * @optional
+ */
+ childContextTypes: SpecPolicy.DEFINE_MANY,
+
+ // ==== Definition methods ====
+
+ /**
+ * Invoked when the component is mounted. Values in the mapping will be set on
+ * `this.props` if that prop is not specified (i.e. using an `in` check).
+ *
+ * This method is invoked before `getInitialState` and therefore cannot rely
+ * on `this.state` or use `this.setState`.
+ *
+ * @return {object}
+ * @optional
+ */
+ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
+
+ /**
+ * Invoked once before the component is mounted. The return value will be used
+ * as the initial value of `this.state`.
+ *
+ * getInitialState: function() {
+ * return {
+ * isOn: false,
+ * fooBaz: new BazFoo()
+ * }
+ * }
+ *
+ * @return {object}
+ * @optional
+ */
+ getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
+
+ /**
+ * @return {object}
+ * @optional
+ */
+ getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
+
+ /**
+ * Uses props from `this.props` and state from `this.state` to render the
+ * structure of the component.
+ *
+ * No guarantees are made about when or how often this method is invoked, so
+ * it must not have side effects.
+ *
+ * render: function() {
+ * var name = this.props.name;
+ * return
Hello, {name}!
;
+ * }
+ *
+ * @return {ReactComponent}
+ * @nosideeffects
+ * @required
+ */
+ render: SpecPolicy.DEFINE_ONCE,
+
+
+
+ // ==== Delegate methods ====
+
+ /**
+ * Invoked when the component is initially created and about to be mounted.
+ * This may have side effects, but any external subscriptions or data created
+ * by this method must be cleaned up in `componentWillUnmount`.
+ *
+ * @optional
+ */
+ componentWillMount: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Invoked when the component has been mounted and has a DOM representation.
+ * However, there is no guarantee that the DOM node is in the document.
+ *
+ * Use this as an opportunity to operate on the DOM when the component has
+ * been mounted (initialized and rendered) for the first time.
+ *
+ * @param {DOMElement} rootNode DOM element representing the component.
+ * @optional
+ */
+ componentDidMount: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Invoked before the component receives new props.
+ *
+ * Use this as an opportunity to react to a prop transition by updating the
+ * state using `this.setState`. Current props are accessed via `this.props`.
+ *
+ * componentWillReceiveProps: function(nextProps, nextContext) {
+ * this.setState({
+ * likesIncreasing: nextProps.likeCount > this.props.likeCount
+ * });
+ * }
+ *
+ * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
+ * transition may cause a state change, but the opposite is not true. If you
+ * need it, you are probably looking for `componentWillUpdate`.
+ *
+ * @param {object} nextProps
+ * @optional
+ */
+ componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Invoked while deciding if the component should be updated as a result of
+ * receiving new props, state and/or context.
+ *
+ * Use this as an opportunity to `return false` when you're certain that the
+ * transition to the new props/state/context will not require a component
+ * update.
+ *
+ * shouldComponentUpdate: function(nextProps, nextState, nextContext) {
+ * return !equal(nextProps, this.props) ||
+ * !equal(nextState, this.state) ||
+ * !equal(nextContext, this.context);
+ * }
+ *
+ * @param {object} nextProps
+ * @param {?object} nextState
+ * @param {?object} nextContext
+ * @return {boolean} True if the component should update.
+ * @optional
+ */
+ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
+
+ /**
+ * Invoked when the component is about to update due to a transition from
+ * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
+ * and `nextContext`.
+ *
+ * Use this as an opportunity to perform preparation before an update occurs.
+ *
+ * NOTE: You **cannot** use `this.setState()` in this method.
+ *
+ * @param {object} nextProps
+ * @param {?object} nextState
+ * @param {?object} nextContext
+ * @param {ReactReconcileTransaction} transaction
+ * @optional
+ */
+ componentWillUpdate: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Invoked when the component's DOM representation has been updated.
+ *
+ * Use this as an opportunity to operate on the DOM when the component has
+ * been updated.
+ *
+ * @param {object} prevProps
+ * @param {?object} prevState
+ * @param {?object} prevContext
+ * @param {DOMElement} rootNode DOM element representing the component.
+ * @optional
+ */
+ componentDidUpdate: SpecPolicy.DEFINE_MANY,
+
+ /**
+ * Invoked when the component is about to be removed from its parent and have
+ * its DOM representation destroyed.
+ *
+ * Use this as an opportunity to deallocate any external resources.
+ *
+ * NOTE: There is no `componentDidUnmount` since your component will have been
+ * destroyed by that point.
+ *
+ * @optional
+ */
+ componentWillUnmount: SpecPolicy.DEFINE_MANY,
+
+
+
+ // ==== Advanced methods ====
+
+ /**
+ * Updates the component's currently mounted DOM representation.
+ *
+ * By default, this implements React's rendering and reconciliation algorithm.
+ * Sophisticated clients may wish to override this.
+ *
+ * @param {ReactReconcileTransaction} transaction
+ * @internal
+ * @overridable
+ */
+ updateComponent: SpecPolicy.OVERRIDE_BASE
+
+ };
+
+ /**
+ * Mapping from class specification keys to special processing functions.
+ *
+ * Although these are declared like instance properties in the specification
+ * when defining classes using `React.createClass`, they are actually static
+ * and are accessible on the constructor instead of the prototype. Despite
+ * being static, they must be defined outside of the "statics" key under
+ * which all other static methods are defined.
+ */
+ var RESERVED_SPEC_KEYS = {
+ displayName: function(Constructor, displayName) {
+ Constructor.displayName = displayName;
+ },
+ mixins: function(Constructor, mixins) {
+ if (mixins) {
+ for (var i = 0; i < mixins.length; i++) {
+ mixSpecIntoComponent(Constructor, mixins[i]);
+ }
+ }
+ },
+ childContextTypes: function(Constructor, childContextTypes) {
+ if ("production" !== process.env.NODE_ENV) {
+ validateTypeDef(
+ Constructor,
+ childContextTypes,
+ ReactPropTypeLocations.childContext
+ );
+ }
+ Constructor.childContextTypes = assign(
+ {},
+ Constructor.childContextTypes,
+ childContextTypes
+ );
+ },
+ contextTypes: function(Constructor, contextTypes) {
+ if ("production" !== process.env.NODE_ENV) {
+ validateTypeDef(
+ Constructor,
+ contextTypes,
+ ReactPropTypeLocations.context
+ );
+ }
+ Constructor.contextTypes = assign(
+ {},
+ Constructor.contextTypes,
+ contextTypes
+ );
+ },
+ /**
+ * Special case getDefaultProps which should move into statics but requires
+ * automatic merging.
+ */
+ getDefaultProps: function(Constructor, getDefaultProps) {
+ if (Constructor.getDefaultProps) {
+ Constructor.getDefaultProps = createMergedResultFunction(
+ Constructor.getDefaultProps,
+ getDefaultProps
+ );
+ } else {
+ Constructor.getDefaultProps = getDefaultProps;
+ }
+ },
+ propTypes: function(Constructor, propTypes) {
+ if ("production" !== process.env.NODE_ENV) {
+ validateTypeDef(
+ Constructor,
+ propTypes,
+ ReactPropTypeLocations.prop
+ );
+ }
+ Constructor.propTypes = assign(
+ {},
+ Constructor.propTypes,
+ propTypes
+ );
+ },
+ statics: function(Constructor, statics) {
+ mixStaticSpecIntoComponent(Constructor, statics);
+ }
+ };
+
+ function validateTypeDef(Constructor, typeDef, location) {
+ for (var propName in typeDef) {
+ if (typeDef.hasOwnProperty(propName)) {
+ // use a warning instead of an invariant so components
+ // don't show up in prod but not in __DEV__
+ ("production" !== process.env.NODE_ENV ? warning(
+ typeof typeDef[propName] === 'function',
+ '%s: %s type `%s` is invalid; it must be a function, usually from ' +
+ 'React.PropTypes.',
+ Constructor.displayName || 'ReactClass',
+ ReactPropTypeLocationNames[location],
+ propName
+ ) : null);
+ }
+ }
+ }
+
+ function validateMethodOverride(proto, name) {
+ var specPolicy = ReactClassInterface.hasOwnProperty(name) ?
+ ReactClassInterface[name] :
+ null;
+
+ // Disallow overriding of base class methods unless explicitly allowed.
+ if (ReactClassMixin.hasOwnProperty(name)) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ specPolicy === SpecPolicy.OVERRIDE_BASE,
+ 'ReactClassInterface: You are attempting to override ' +
+ '`%s` from your class specification. Ensure that your method names ' +
+ 'do not overlap with React methods.',
+ name
+ ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
+ }
+
+ // Disallow defining methods more than once unless explicitly allowed.
+ if (proto.hasOwnProperty(name)) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ specPolicy === SpecPolicy.DEFINE_MANY ||
+ specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
+ 'ReactClassInterface: You are attempting to define ' +
+ '`%s` on your component more than once. This conflict may be due ' +
+ 'to a mixin.',
+ name
+ ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
+ specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
+ }
+ }
+
+ /**
+ * Mixin helper which handles policy validation and reserved
+ * specification keys when building React classses.
+ */
+ function mixSpecIntoComponent(Constructor, spec) {
+ if (!spec) {
+ return;
+ }
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof spec !== 'function',
+ 'ReactClass: You\'re attempting to ' +
+ 'use a component class as a mixin. Instead, just use a regular object.'
+ ) : invariant(typeof spec !== 'function'));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !ReactElement.isValidElement(spec),
+ 'ReactClass: You\'re attempting to ' +
+ 'use a component as a mixin. Instead, just use a regular object.'
+ ) : invariant(!ReactElement.isValidElement(spec)));
+
+ var proto = Constructor.prototype;
+
+ // By handling mixins before any other properties, we ensure the same
+ // chaining order is applied to methods with DEFINE_MANY policy, whether
+ // mixins are listed before or after these methods in the spec.
+ if (spec.hasOwnProperty(MIXINS_KEY)) {
+ RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
+ }
+
+ for (var name in spec) {
+ if (!spec.hasOwnProperty(name)) {
+ continue;
+ }
+
+ if (name === MIXINS_KEY) {
+ // We have already handled mixins in a special case above
+ continue;
+ }
+
+ var property = spec[name];
+ validateMethodOverride(proto, name);
+
+ if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
+ RESERVED_SPEC_KEYS[name](Constructor, property);
+ } else {
+ // Setup methods on prototype:
+ // The following member methods should not be automatically bound:
+ // 1. Expected ReactClass methods (in the "interface").
+ // 2. Overridden methods (that were mixed in).
+ var isReactClassMethod =
+ ReactClassInterface.hasOwnProperty(name);
+ var isAlreadyDefined = proto.hasOwnProperty(name);
+ var markedDontBind = property && property.__reactDontBind;
+ var isFunction = typeof property === 'function';
+ var shouldAutoBind =
+ isFunction &&
+ !isReactClassMethod &&
+ !isAlreadyDefined &&
+ !markedDontBind;
+
+ if (shouldAutoBind) {
+ if (!proto.__reactAutoBindMap) {
+ proto.__reactAutoBindMap = {};
+ }
+ proto.__reactAutoBindMap[name] = property;
+ proto[name] = property;
+ } else {
+ if (isAlreadyDefined) {
+ var specPolicy = ReactClassInterface[name];
+
+ // These cases should already be caught by validateMethodOverride
+ ("production" !== process.env.NODE_ENV ? invariant(
+ isReactClassMethod && (
+ (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)
+ ),
+ 'ReactClass: Unexpected spec policy %s for key %s ' +
+ 'when mixing in component specs.',
+ specPolicy,
+ name
+ ) : invariant(isReactClassMethod && (
+ (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)
+ )));
+
+ // For methods which are defined more than once, call the existing
+ // methods before calling the new property, merging if appropriate.
+ if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
+ proto[name] = createMergedResultFunction(proto[name], property);
+ } else if (specPolicy === SpecPolicy.DEFINE_MANY) {
+ proto[name] = createChainedFunction(proto[name], property);
+ }
+ } else {
+ proto[name] = property;
+ if ("production" !== process.env.NODE_ENV) {
+ // Add verbose displayName to the function, which helps when looking
+ // at profiling tools.
+ if (typeof property === 'function' && spec.displayName) {
+ proto[name].displayName = spec.displayName + '_' + name;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ function mixStaticSpecIntoComponent(Constructor, statics) {
+ if (!statics) {
+ return;
+ }
+ for (var name in statics) {
+ var property = statics[name];
+ if (!statics.hasOwnProperty(name)) {
+ continue;
+ }
+
+ var isReserved = name in RESERVED_SPEC_KEYS;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !isReserved,
+ 'ReactClass: You are attempting to define a reserved ' +
+ 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
+ 'as an instance property instead; it will still be accessible on the ' +
+ 'constructor.',
+ name
+ ) : invariant(!isReserved));
+
+ var isInherited = name in Constructor;
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !isInherited,
+ 'ReactClass: You are attempting to define ' +
+ '`%s` on your component more than once. This conflict may be ' +
+ 'due to a mixin.',
+ name
+ ) : invariant(!isInherited));
+ Constructor[name] = property;
+ }
+ }
+
+ /**
+ * Merge two objects, but throw if both contain the same key.
+ *
+ * @param {object} one The first object, which is mutated.
+ * @param {object} two The second object
+ * @return {object} one after it has been mutated to contain everything in two.
+ */
+ function mergeIntoWithNoDuplicateKeys(one, two) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ one && two && typeof one === 'object' && typeof two === 'object',
+ 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
+ ) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
+
+ for (var key in two) {
+ if (two.hasOwnProperty(key)) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ one[key] === undefined,
+ 'mergeIntoWithNoDuplicateKeys(): ' +
+ 'Tried to merge two objects with the same key: `%s`. This conflict ' +
+ 'may be due to a mixin; in particular, this may be caused by two ' +
+ 'getInitialState() or getDefaultProps() methods returning objects ' +
+ 'with clashing keys.',
+ key
+ ) : invariant(one[key] === undefined));
+ one[key] = two[key];
+ }
+ }
+ return one;
+ }
+
+ /**
+ * Creates a function that invokes two functions and merges their return values.
+ *
+ * @param {function} one Function to invoke first.
+ * @param {function} two Function to invoke second.
+ * @return {function} Function that invokes the two argument functions.
+ * @private
+ */
+ function createMergedResultFunction(one, two) {
+ return function mergedResult() {
+ var a = one.apply(this, arguments);
+ var b = two.apply(this, arguments);
+ if (a == null) {
+ return b;
+ } else if (b == null) {
+ return a;
+ }
+ var c = {};
+ mergeIntoWithNoDuplicateKeys(c, a);
+ mergeIntoWithNoDuplicateKeys(c, b);
+ return c;
+ };
+ }
+
+ /**
+ * Creates a function that invokes two functions and ignores their return vales.
+ *
+ * @param {function} one Function to invoke first.
+ * @param {function} two Function to invoke second.
+ * @return {function} Function that invokes the two argument functions.
+ * @private
+ */
+ function createChainedFunction(one, two) {
+ return function chainedFunction() {
+ one.apply(this, arguments);
+ two.apply(this, arguments);
+ };
+ }
+
+ /**
+ * Binds a method to the component.
+ *
+ * @param {object} component Component whose method is going to be bound.
+ * @param {function} method Method to be bound.
+ * @return {function} The bound method.
+ */
+ function bindAutoBindMethod(component, method) {
+ var boundMethod = method.bind(component);
+ if ("production" !== process.env.NODE_ENV) {
+ boundMethod.__reactBoundContext = component;
+ boundMethod.__reactBoundMethod = method;
+ boundMethod.__reactBoundArguments = null;
+ var componentName = component.constructor.displayName;
+ var _bind = boundMethod.bind;
+ /* eslint-disable block-scoped-var, no-undef */
+ boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
+ // User is trying to bind() an autobound method; we effectively will
+ // ignore the value of "this" that the user is trying to use, so
+ // let's warn.
+ if (newThis !== component && newThis !== null) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'bind(): React component methods may only be bound to the ' +
+ 'component instance. See %s',
+ componentName
+ ) : null);
+ } else if (!args.length) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ 'bind(): You are binding a component method to the component. ' +
+ 'React does this for you automatically in a high-performance ' +
+ 'way, so you can safely remove this call. See %s',
+ componentName
+ ) : null);
+ return boundMethod;
+ }
+ var reboundMethod = _bind.apply(boundMethod, arguments);
+ reboundMethod.__reactBoundContext = component;
+ reboundMethod.__reactBoundMethod = method;
+ reboundMethod.__reactBoundArguments = args;
+ return reboundMethod;
+ /* eslint-enable */
+ };
+ }
+ return boundMethod;
+ }
+
+ /**
+ * Binds all auto-bound methods in a component.
+ *
+ * @param {object} component Component whose method is going to be bound.
+ */
+ function bindAutoBindMethods(component) {
+ for (var autoBindKey in component.__reactAutoBindMap) {
+ if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
+ var method = component.__reactAutoBindMap[autoBindKey];
+ component[autoBindKey] = bindAutoBindMethod(
+ component,
+ ReactErrorUtils.guard(
+ method,
+ component.constructor.displayName + '.' + autoBindKey
+ )
+ );
+ }
+ }
+ }
+
+ var typeDeprecationDescriptor = {
+ enumerable: false,
+ get: function() {
+ var displayName = this.displayName || this.name || 'Component';
+ ("production" !== process.env.NODE_ENV ? warning(
+ false,
+ '%s.type is deprecated. Use %s directly to access the class.',
+ displayName,
+ displayName
+ ) : null);
+ Object.defineProperty(this, 'type', {
+ value: this
+ });
+ return this;
+ }
+ };
+
+ /**
+ * Add more to the ReactClass base class. These are all legacy features and
+ * therefore not already part of the modern ReactComponent.
+ */
+ var ReactClassMixin = {
+
+ /**
+ * TODO: This will be deprecated because state should always keep a consistent
+ * type signature and the only use case for this, is to avoid that.
+ */
+ replaceState: function(newState, callback) {
+ ReactUpdateQueue.enqueueReplaceState(this, newState);
+ if (callback) {
+ ReactUpdateQueue.enqueueCallback(this, callback);
+ }
+ },
+
+ /**
+ * Checks whether or not this composite component is mounted.
+ * @return {boolean} True if mounted, false otherwise.
+ * @protected
+ * @final
+ */
+ isMounted: function() {
+ if ("production" !== process.env.NODE_ENV) {
+ var owner = ReactCurrentOwner.current;
+ if (owner !== null) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ owner._warnedAboutRefsInRender,
+ '%s is accessing isMounted inside its render() function. ' +
+ 'render() should be a pure function of props and state. It should ' +
+ 'never access something that requires stale data from the previous ' +
+ 'render, such as refs. Move this logic to componentDidMount and ' +
+ 'componentDidUpdate instead.',
+ owner.getName() || 'A component'
+ ) : null);
+ owner._warnedAboutRefsInRender = true;
+ }
+ }
+ var internalInstance = ReactInstanceMap.get(this);
+ return (
+ internalInstance &&
+ internalInstance !== ReactLifeCycle.currentlyMountingInstance
+ );
+ },
+
+ /**
+ * Sets a subset of the props.
+ *
+ * @param {object} partialProps Subset of the next props.
+ * @param {?function} callback Called after props are updated.
+ * @final
+ * @public
+ * @deprecated
+ */
+ setProps: function(partialProps, callback) {
+ ReactUpdateQueue.enqueueSetProps(this, partialProps);
+ if (callback) {
+ ReactUpdateQueue.enqueueCallback(this, callback);
+ }
+ },
+
+ /**
+ * Replace all the props.
+ *
+ * @param {object} newProps Subset of the next props.
+ * @param {?function} callback Called after props are updated.
+ * @final
+ * @public
+ * @deprecated
+ */
+ replaceProps: function(newProps, callback) {
+ ReactUpdateQueue.enqueueReplaceProps(this, newProps);
+ if (callback) {
+ ReactUpdateQueue.enqueueCallback(this, callback);
+ }
+ }
+ };
+
+ var ReactClassComponent = function() {};
+ assign(
+ ReactClassComponent.prototype,
+ ReactComponent.prototype,
+ ReactClassMixin
+ );
+
+ /**
+ * Module for creating composite components.
+ *
+ * @class ReactClass
+ */
+ var ReactClass = {
+
+ /**
+ * Creates a composite component class given a class specification.
+ *
+ * @param {object} spec Class specification (which must define `render`).
+ * @return {function} Component constructor function.
+ * @public
+ */
+ createClass: function(spec) {
+ var Constructor = function(props, context) {
+ // This constructor is overridden by mocks. The argument is used
+ // by mocks to assert on what gets mounted.
+
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ this instanceof Constructor,
+ 'Something is calling a React component directly. Use a factory or ' +
+ 'JSX instead. See: https://fb.me/react-legacyfactory'
+ ) : null);
+ }
+
+ // Wire up auto-binding
+ if (this.__reactAutoBindMap) {
+ bindAutoBindMethods(this);
+ }
+
+ this.props = props;
+ this.context = context;
+ this.state = null;
+
+ // ReactClasses doesn't have constructors. Instead, they use the
+ // getInitialState and componentWillMount methods for initialization.
+
+ var initialState = this.getInitialState ? this.getInitialState() : null;
+ if ("production" !== process.env.NODE_ENV) {
+ // We allow auto-mocks to proceed as if they're returning null.
+ if (typeof initialState === 'undefined' &&
+ this.getInitialState._isMockFunction) {
+ // This is probably bad practice. Consider warning here and
+ // deprecating this convenience.
+ initialState = null;
+ }
+ }
+ ("production" !== process.env.NODE_ENV ? invariant(
+ typeof initialState === 'object' && !Array.isArray(initialState),
+ '%s.getInitialState(): must return an object or null',
+ Constructor.displayName || 'ReactCompositeComponent'
+ ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
+
+ this.state = initialState;
+ };
+ Constructor.prototype = new ReactClassComponent();
+ Constructor.prototype.constructor = Constructor;
+
+ injectedMixins.forEach(
+ mixSpecIntoComponent.bind(null, Constructor)
+ );
+
+ mixSpecIntoComponent(Constructor, spec);
+
+ // Initialize the defaultProps property after all mixins have been merged
+ if (Constructor.getDefaultProps) {
+ Constructor.defaultProps = Constructor.getDefaultProps();
+ }
+
+ if ("production" !== process.env.NODE_ENV) {
+ // This is a tag to indicate that the use of these method names is ok,
+ // since it's used with createClass. If it's not, then it's likely a
+ // mistake so we'll warn you to use the static property, property
+ // initializer or constructor respectively.
+ if (Constructor.getDefaultProps) {
+ Constructor.getDefaultProps.isReactClassApproved = {};
+ }
+ if (Constructor.prototype.getInitialState) {
+ Constructor.prototype.getInitialState.isReactClassApproved = {};
+ }
+ }
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ Constructor.prototype.render,
+ 'createClass(...): Class specification must implement a `render` method.'
+ ) : invariant(Constructor.prototype.render));
+
+ if ("production" !== process.env.NODE_ENV) {
+ ("production" !== process.env.NODE_ENV ? warning(
+ !Constructor.prototype.componentShouldUpdate,
+ '%s has a method called ' +
+ 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
+ 'The name is phrased as a question because the function is ' +
+ 'expected to return a value.',
+ spec.displayName || 'A component'
+ ) : null);
+ }
+
+ // Reduce time spent doing lookups by setting these on the prototype.
+ for (var methodName in ReactClassInterface) {
+ if (!Constructor.prototype[methodName]) {
+ Constructor.prototype[methodName] = null;
+ }
+ }
+
+ // Legacy hook
+ Constructor.type = Constructor;
+ if ("production" !== process.env.NODE_ENV) {
+ try {
+ Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor);
+ } catch (x) {
+ // IE will fail on defineProperty (es5-shim/sham too)
+ }
+ }
+
+ return Constructor;
+ },
+
+ injection: {
+ injectMixin: function(mixin) {
+ injectedMixins.push(mixin);
+ }
+ }
+
+ };
+
+ module.exports = ReactClass;
+
+
+/***/ },
+/* 89 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactErrorUtils
+ * @typechecks
+ */
+
+ "use strict";
+
+ var ReactErrorUtils = {
+ /**
+ * Creates a guarded version of a function. This is supposed to make debugging
+ * of event handlers easier. To aid debugging with the browser's debugger,
+ * this currently simply returns the original function.
+ *
+ * @param {function} func Function to be executed
+ * @param {string} name The name of the guard
+ * @return {function}
+ */
+ guard: function(func, name) {
+ return func;
+ }
+ };
+
+ module.exports = ReactErrorUtils;
+
+
+/***/ },
+/* 90 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule keyOf
+ */
+
+ /**
+ * Allows extraction of a minified key. Let's the build system minify keys
+ * without loosing the ability to dynamically use key strings as values
+ * themselves. Pass in an object with a single key/val pair and it will return
+ * you the string key of that single record. Suppose you want to grab the
+ * value for a key 'className' inside of an object. Key/val minification may
+ * have aliased that key to be 'xa12'. keyOf({className: null}) will return
+ * 'xa12' in that case. Resolve keys you want to use once at startup time, then
+ * reuse those resolutions.
+ */
+ var keyOf = function(oneKeyObj) {
+ var key;
+ for (key in oneKeyObj) {
+ if (!oneKeyObj.hasOwnProperty(key)) {
+ continue;
+ }
+ return key;
+ }
+ return null;
+ };
+
+
+ module.exports = keyOf;
+
+
+/***/ },
+/* 91 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactDOM
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ var ReactElement = __webpack_require__(62);
+ var ReactElementValidator = __webpack_require__(81);
+
+ var mapObject = __webpack_require__(92);
+
+ /**
+ * Create a factory that creates HTML tag elements.
+ *
+ * @param {string} tag Tag name (e.g. `div`).
+ * @private
+ */
+ function createDOMFactory(tag) {
+ if ("production" !== process.env.NODE_ENV) {
+ return ReactElementValidator.createFactory(tag);
+ }
+ return ReactElement.createFactory(tag);
+ }
+
+ /**
+ * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
+ * This is also accessible via `React.DOM`.
+ *
+ * @public
+ */
+ var ReactDOM = mapObject({
+ a: 'a',
+ abbr: 'abbr',
+ address: 'address',
+ area: 'area',
+ article: 'article',
+ aside: 'aside',
+ audio: 'audio',
+ b: 'b',
+ base: 'base',
+ bdi: 'bdi',
+ bdo: 'bdo',
+ big: 'big',
+ blockquote: 'blockquote',
+ body: 'body',
+ br: 'br',
+ button: 'button',
+ canvas: 'canvas',
+ caption: 'caption',
+ cite: 'cite',
+ code: 'code',
+ col: 'col',
+ colgroup: 'colgroup',
+ data: 'data',
+ datalist: 'datalist',
+ dd: 'dd',
+ del: 'del',
+ details: 'details',
+ dfn: 'dfn',
+ dialog: 'dialog',
+ div: 'div',
+ dl: 'dl',
+ dt: 'dt',
+ em: 'em',
+ embed: 'embed',
+ fieldset: 'fieldset',
+ figcaption: 'figcaption',
+ figure: 'figure',
+ footer: 'footer',
+ form: 'form',
+ h1: 'h1',
+ h2: 'h2',
+ h3: 'h3',
+ h4: 'h4',
+ h5: 'h5',
+ h6: 'h6',
+ head: 'head',
+ header: 'header',
+ hr: 'hr',
+ html: 'html',
+ i: 'i',
+ iframe: 'iframe',
+ img: 'img',
+ input: 'input',
+ ins: 'ins',
+ kbd: 'kbd',
+ keygen: 'keygen',
+ label: 'label',
+ legend: 'legend',
+ li: 'li',
+ link: 'link',
+ main: 'main',
+ map: 'map',
+ mark: 'mark',
+ menu: 'menu',
+ menuitem: 'menuitem',
+ meta: 'meta',
+ meter: 'meter',
+ nav: 'nav',
+ noscript: 'noscript',
+ object: 'object',
+ ol: 'ol',
+ optgroup: 'optgroup',
+ option: 'option',
+ output: 'output',
+ p: 'p',
+ param: 'param',
+ picture: 'picture',
+ pre: 'pre',
+ progress: 'progress',
+ q: 'q',
+ rp: 'rp',
+ rt: 'rt',
+ ruby: 'ruby',
+ s: 's',
+ samp: 'samp',
+ script: 'script',
+ section: 'section',
+ select: 'select',
+ small: 'small',
+ source: 'source',
+ span: 'span',
+ strong: 'strong',
+ style: 'style',
+ sub: 'sub',
+ summary: 'summary',
+ sup: 'sup',
+ table: 'table',
+ tbody: 'tbody',
+ td: 'td',
+ textarea: 'textarea',
+ tfoot: 'tfoot',
+ th: 'th',
+ thead: 'thead',
+ time: 'time',
+ title: 'title',
+ tr: 'tr',
+ track: 'track',
+ u: 'u',
+ ul: 'ul',
+ 'var': 'var',
+ video: 'video',
+ wbr: 'wbr',
+
+ // SVG
+ circle: 'circle',
+ clipPath: 'clipPath',
+ defs: 'defs',
+ ellipse: 'ellipse',
+ g: 'g',
+ line: 'line',
+ linearGradient: 'linearGradient',
+ mask: 'mask',
+ path: 'path',
+ pattern: 'pattern',
+ polygon: 'polygon',
+ polyline: 'polyline',
+ radialGradient: 'radialGradient',
+ rect: 'rect',
+ stop: 'stop',
+ svg: 'svg',
+ text: 'text',
+ tspan: 'tspan'
+
+ }, createDOMFactory);
+
+ module.exports = ReactDOM;
+
+
+/***/ },
+/* 92 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule mapObject
+ */
+
+ 'use strict';
+
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+ /**
+ * Executes the provided `callback` once for each enumerable own property in the
+ * object and constructs a new object from the results. The `callback` is
+ * invoked with three arguments:
+ *
+ * - the property value
+ * - the property name
+ * - the object being traversed
+ *
+ * Properties that are added after the call to `mapObject` will not be visited
+ * by `callback`. If the values of existing properties are changed, the value
+ * passed to `callback` will be the value at the time `mapObject` visits them.
+ * Properties that are deleted before being visited are not visited.
+ *
+ * @grep function objectMap()
+ * @grep function objMap()
+ *
+ * @param {?object} object
+ * @param {function} callback
+ * @param {*} context
+ * @return {?object}
+ */
+ function mapObject(object, callback, context) {
+ if (!object) {
+ return null;
+ }
+ var result = {};
+ for (var name in object) {
+ if (hasOwnProperty.call(object, name)) {
+ result[name] = callback.call(context, object[name], name, object);
+ }
+ }
+ return result;
+ }
+
+ module.exports = mapObject;
+
+
+/***/ },
+/* 93 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactDOMTextComponent
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ var DOMPropertyOperations = __webpack_require__(94);
+ var ReactComponentBrowserEnvironment =
+ __webpack_require__(98);
+ var ReactDOMComponent = __webpack_require__(138);
+
+ var assign = __webpack_require__(64);
+ var escapeTextContentForBrowser = __webpack_require__(97);
+
+ /**
+ * Text nodes violate a couple assumptions that React makes about components:
+ *
+ * - When mounting text into the DOM, adjacent text nodes are merged.
+ * - Text nodes cannot be assigned a React root ID.
+ *
+ * This component is used to wrap strings in elements so that they can undergo
+ * the same reconciliation that is applied to elements.
+ *
+ * TODO: Investigate representing React components in the DOM with text nodes.
+ *
+ * @class ReactDOMTextComponent
+ * @extends ReactComponent
+ * @internal
+ */
+ var ReactDOMTextComponent = function(props) {
+ // This constructor and its argument is currently used by mocks.
+ };
+
+ assign(ReactDOMTextComponent.prototype, {
+
+ /**
+ * @param {ReactText} text
+ * @internal
+ */
+ construct: function(text) {
+ // TODO: This is really a ReactText (ReactNode), not a ReactElement
+ this._currentElement = text;
+ this._stringText = '' + text;
+
+ // Properties
+ this._rootNodeID = null;
+ this._mountIndex = 0;
+ },
+
+ /**
+ * Creates the markup for this text node. This node is not intended to have
+ * any features besides containing text content.
+ *
+ * @param {string} rootID DOM ID of the root node.
+ * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
+ * @return {string} Markup for this text node.
+ * @internal
+ */
+ mountComponent: function(rootID, transaction, context) {
+ this._rootNodeID = rootID;
+ var escapedText = escapeTextContentForBrowser(this._stringText);
+
+ if (transaction.renderToStaticMarkup) {
+ // Normally we'd wrap this in a `span` for the reasons stated above, but
+ // since this is a situation where React won't take over (static pages),
+ // we can simply return the text as it is.
+ return escapedText;
+ }
+
+ return (
+ '' +
+ escapedText +
+ ''
+ );
+ },
+
+ /**
+ * Updates this component by updating the text content.
+ *
+ * @param {ReactText} nextText The next text content
+ * @param {ReactReconcileTransaction} transaction
+ * @internal
+ */
+ receiveComponent: function(nextText, transaction) {
+ if (nextText !== this._currentElement) {
+ this._currentElement = nextText;
+ var nextStringText = '' + nextText;
+ if (nextStringText !== this._stringText) {
+ // TODO: Save this as pending props and use performUpdateIfNecessary
+ // and/or updateComponent to do the actual update for consistency with
+ // other component types?
+ this._stringText = nextStringText;
+ ReactDOMComponent.BackendIDOperations.updateTextContentByID(
+ this._rootNodeID,
+ nextStringText
+ );
+ }
+ }
+ },
+
+ unmountComponent: function() {
+ ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
+ }
+
+ });
+
+ module.exports = ReactDOMTextComponent;
+
+
+/***/ },
+/* 94 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule DOMPropertyOperations
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ var DOMProperty = __webpack_require__(95);
+
+ var quoteAttributeValueForBrowser = __webpack_require__(96);
+ var warning = __webpack_require__(66);
+
+ function shouldIgnoreValue(name, value) {
+ return value == null ||
+ (DOMProperty.hasBooleanValue[name] && !value) ||
+ (DOMProperty.hasNumericValue[name] && isNaN(value)) ||
+ (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) ||
+ (DOMProperty.hasOverloadedBooleanValue[name] && value === false);
+ }
+
+ if ("production" !== process.env.NODE_ENV) {
+ var reactProps = {
+ children: true,
+ dangerouslySetInnerHTML: true,
+ key: true,
+ ref: true
+ };
+ var warnedProperties = {};
+
+ var warnUnknownProperty = function(name) {
+ if (reactProps.hasOwnProperty(name) && reactProps[name] ||
+ warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
+ return;
+ }
+
+ warnedProperties[name] = true;
+ var lowerCasedName = name.toLowerCase();
+
+ // data-* attributes should be lowercase; suggest the lowercase version
+ var standardName = (
+ DOMProperty.isCustomAttribute(lowerCasedName) ?
+ lowerCasedName :
+ DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ?
+ DOMProperty.getPossibleStandardName[lowerCasedName] :
+ null
+ );
+
+ // For now, only warn when we have a suggested correction. This prevents
+ // logging too much when using transferPropsTo.
+ ("production" !== process.env.NODE_ENV ? warning(
+ standardName == null,
+ 'Unknown DOM property %s. Did you mean %s?',
+ name,
+ standardName
+ ) : null);
+
+ };
+ }
+
+ /**
+ * Operations for dealing with DOM properties.
+ */
+ var DOMPropertyOperations = {
+
+ /**
+ * Creates markup for the ID property.
+ *
+ * @param {string} id Unescaped ID.
+ * @return {string} Markup string.
+ */
+ createMarkupForID: function(id) {
+ return DOMProperty.ID_ATTRIBUTE_NAME + '=' +
+ quoteAttributeValueForBrowser(id);
+ },
+
+ /**
+ * Creates markup for a property.
+ *
+ * @param {string} name
+ * @param {*} value
+ * @return {?string} Markup string, or null if the property was invalid.
+ */
+ createMarkupForProperty: function(name, value) {
+ if (DOMProperty.isStandardName.hasOwnProperty(name) &&
+ DOMProperty.isStandardName[name]) {
+ if (shouldIgnoreValue(name, value)) {
+ return '';
+ }
+ var attributeName = DOMProperty.getAttributeName[name];
+ if (DOMProperty.hasBooleanValue[name] ||
+ (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) {
+ return attributeName;
+ }
+ return attributeName + '=' + quoteAttributeValueForBrowser(value);
+ } else if (DOMProperty.isCustomAttribute(name)) {
+ if (value == null) {
+ return '';
+ }
+ return name + '=' + quoteAttributeValueForBrowser(value);
+ } else if ("production" !== process.env.NODE_ENV) {
+ warnUnknownProperty(name);
+ }
+ return null;
+ },
+
+ /**
+ * Sets the value for a property on a node.
+ *
+ * @param {DOMElement} node
+ * @param {string} name
+ * @param {*} value
+ */
+ setValueForProperty: function(node, name, value) {
+ if (DOMProperty.isStandardName.hasOwnProperty(name) &&
+ DOMProperty.isStandardName[name]) {
+ var mutationMethod = DOMProperty.getMutationMethod[name];
+ if (mutationMethod) {
+ mutationMethod(node, value);
+ } else if (shouldIgnoreValue(name, value)) {
+ this.deleteValueForProperty(node, name);
+ } else if (DOMProperty.mustUseAttribute[name]) {
+ // `setAttribute` with objects becomes only `[object]` in IE8/9,
+ // ('' + value) makes it output the correct toString()-value.
+ node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
+ } else {
+ var propName = DOMProperty.getPropertyName[name];
+ // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
+ // property type before comparing; only `value` does and is string.
+ if (!DOMProperty.hasSideEffects[name] ||
+ ('' + node[propName]) !== ('' + value)) {
+ // Contrary to `setAttribute`, object properties are properly
+ // `toString`ed by IE8/9.
+ node[propName] = value;
+ }
+ }
+ } else if (DOMProperty.isCustomAttribute(name)) {
+ if (value == null) {
+ node.removeAttribute(name);
+ } else {
+ node.setAttribute(name, '' + value);
+ }
+ } else if ("production" !== process.env.NODE_ENV) {
+ warnUnknownProperty(name);
+ }
+ },
+
+ /**
+ * Deletes the value for a property on a node.
+ *
+ * @param {DOMElement} node
+ * @param {string} name
+ */
+ deleteValueForProperty: function(node, name) {
+ if (DOMProperty.isStandardName.hasOwnProperty(name) &&
+ DOMProperty.isStandardName[name]) {
+ var mutationMethod = DOMProperty.getMutationMethod[name];
+ if (mutationMethod) {
+ mutationMethod(node, undefined);
+ } else if (DOMProperty.mustUseAttribute[name]) {
+ node.removeAttribute(DOMProperty.getAttributeName[name]);
+ } else {
+ var propName = DOMProperty.getPropertyName[name];
+ var defaultValue = DOMProperty.getDefaultValueForProperty(
+ node.nodeName,
+ propName
+ );
+ if (!DOMProperty.hasSideEffects[name] ||
+ ('' + node[propName]) !== defaultValue) {
+ node[propName] = defaultValue;
+ }
+ }
+ } else if (DOMProperty.isCustomAttribute(name)) {
+ node.removeAttribute(name);
+ } else if ("production" !== process.env.NODE_ENV) {
+ warnUnknownProperty(name);
+ }
+ }
+
+ };
+
+ module.exports = DOMPropertyOperations;
+
+
+/***/ },
+/* 95 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule DOMProperty
+ * @typechecks static-only
+ */
+
+ /*jslint bitwise: true */
+
+ 'use strict';
+
+ var invariant = __webpack_require__(58);
+
+ function checkMask(value, bitmask) {
+ return (value & bitmask) === bitmask;
+ }
+
+ var DOMPropertyInjection = {
+ /**
+ * Mapping from normalized, camelcased property names to a configuration that
+ * specifies how the associated DOM property should be accessed or rendered.
+ */
+ MUST_USE_ATTRIBUTE: 0x1,
+ MUST_USE_PROPERTY: 0x2,
+ HAS_SIDE_EFFECTS: 0x4,
+ HAS_BOOLEAN_VALUE: 0x8,
+ HAS_NUMERIC_VALUE: 0x10,
+ HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
+ HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
+
+ /**
+ * Inject some specialized knowledge about the DOM. This takes a config object
+ * with the following properties:
+ *
+ * isCustomAttribute: function that given an attribute name will return true
+ * if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
+ * attributes where it's impossible to enumerate all of the possible
+ * attribute names,
+ *
+ * Properties: object mapping DOM property name to one of the
+ * DOMPropertyInjection constants or null. If your attribute isn't in here,
+ * it won't get written to the DOM.
+ *
+ * DOMAttributeNames: object mapping React attribute name to the DOM
+ * attribute name. Attribute names not specified use the **lowercase**
+ * normalized name.
+ *
+ * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
+ * Property names not specified use the normalized name.
+ *
+ * DOMMutationMethods: Properties that require special mutation methods. If
+ * `value` is undefined, the mutation method should unset the property.
+ *
+ * @param {object} domPropertyConfig the config as described above.
+ */
+ injectDOMPropertyConfig: function(domPropertyConfig) {
+ var Properties = domPropertyConfig.Properties || {};
+ var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
+ var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
+ var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
+
+ if (domPropertyConfig.isCustomAttribute) {
+ DOMProperty._isCustomAttributeFunctions.push(
+ domPropertyConfig.isCustomAttribute
+ );
+ }
+
+ for (var propName in Properties) {
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !DOMProperty.isStandardName.hasOwnProperty(propName),
+ 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
+ '\'%s\' which has already been injected. You may be accidentally ' +
+ 'injecting the same DOM property config twice, or you may be ' +
+ 'injecting two configs that have conflicting property names.',
+ propName
+ ) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName)));
+
+ DOMProperty.isStandardName[propName] = true;
+
+ var lowerCased = propName.toLowerCase();
+ DOMProperty.getPossibleStandardName[lowerCased] = propName;
+
+ if (DOMAttributeNames.hasOwnProperty(propName)) {
+ var attributeName = DOMAttributeNames[propName];
+ DOMProperty.getPossibleStandardName[attributeName] = propName;
+ DOMProperty.getAttributeName[propName] = attributeName;
+ } else {
+ DOMProperty.getAttributeName[propName] = lowerCased;
+ }
+
+ DOMProperty.getPropertyName[propName] =
+ DOMPropertyNames.hasOwnProperty(propName) ?
+ DOMPropertyNames[propName] :
+ propName;
+
+ if (DOMMutationMethods.hasOwnProperty(propName)) {
+ DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName];
+ } else {
+ DOMProperty.getMutationMethod[propName] = null;
+ }
+
+ var propConfig = Properties[propName];
+ DOMProperty.mustUseAttribute[propName] =
+ checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE);
+ DOMProperty.mustUseProperty[propName] =
+ checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY);
+ DOMProperty.hasSideEffects[propName] =
+ checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS);
+ DOMProperty.hasBooleanValue[propName] =
+ checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE);
+ DOMProperty.hasNumericValue[propName] =
+ checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE);
+ DOMProperty.hasPositiveNumericValue[propName] =
+ checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE);
+ DOMProperty.hasOverloadedBooleanValue[propName] =
+ checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE);
+
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !DOMProperty.mustUseAttribute[propName] ||
+ !DOMProperty.mustUseProperty[propName],
+ 'DOMProperty: Cannot require using both attribute and property: %s',
+ propName
+ ) : invariant(!DOMProperty.mustUseAttribute[propName] ||
+ !DOMProperty.mustUseProperty[propName]));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ DOMProperty.mustUseProperty[propName] ||
+ !DOMProperty.hasSideEffects[propName],
+ 'DOMProperty: Properties that have side effects must use property: %s',
+ propName
+ ) : invariant(DOMProperty.mustUseProperty[propName] ||
+ !DOMProperty.hasSideEffects[propName]));
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !!DOMProperty.hasBooleanValue[propName] +
+ !!DOMProperty.hasNumericValue[propName] +
+ !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1,
+ 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
+ 'numeric value, but not a combination: %s',
+ propName
+ ) : invariant(!!DOMProperty.hasBooleanValue[propName] +
+ !!DOMProperty.hasNumericValue[propName] +
+ !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1));
+ }
+ }
+ };
+ var defaultValueCache = {};
+
+ /**
+ * DOMProperty exports lookup objects that can be used like functions:
+ *
+ * > DOMProperty.isValid['id']
+ * true
+ * > DOMProperty.isValid['foobar']
+ * undefined
+ *
+ * Although this may be confusing, it performs better in general.
+ *
+ * @see http://jsperf.com/key-exists
+ * @see http://jsperf.com/key-missing
+ */
+ var DOMProperty = {
+
+ ID_ATTRIBUTE_NAME: 'data-reactid',
+
+ /**
+ * Checks whether a property name is a standard property.
+ * @type {Object}
+ */
+ isStandardName: {},
+
+ /**
+ * Mapping from lowercase property names to the properly cased version, used
+ * to warn in the case of missing properties.
+ * @type {Object}
+ */
+ getPossibleStandardName: {},
+
+ /**
+ * Mapping from normalized names to attribute names that differ. Attribute
+ * names are used when rendering markup or with `*Attribute()`.
+ * @type {Object}
+ */
+ getAttributeName: {},
+
+ /**
+ * Mapping from normalized names to properties on DOM node instances.
+ * (This includes properties that mutate due to external factors.)
+ * @type {Object}
+ */
+ getPropertyName: {},
+
+ /**
+ * Mapping from normalized names to mutation methods. This will only exist if
+ * mutation cannot be set simply by the property or `setAttribute()`.
+ * @type {Object}
+ */
+ getMutationMethod: {},
+
+ /**
+ * Whether the property must be accessed and mutated as an object property.
+ * @type {Object}
+ */
+ mustUseAttribute: {},
+
+ /**
+ * Whether the property must be accessed and mutated using `*Attribute()`.
+ * (This includes anything that fails ` in `.)
+ * @type {Object}
+ */
+ mustUseProperty: {},
+
+ /**
+ * Whether or not setting a value causes side effects such as triggering
+ * resources to be loaded or text selection changes. We must ensure that
+ * the value is only set if it has changed.
+ * @type {Object}
+ */
+ hasSideEffects: {},
+
+ /**
+ * Whether the property should be removed when set to a falsey value.
+ * @type {Object}
+ */
+ hasBooleanValue: {},
+
+ /**
+ * Whether the property must be numeric or parse as a
+ * numeric and should be removed when set to a falsey value.
+ * @type {Object}
+ */
+ hasNumericValue: {},
+
+ /**
+ * Whether the property must be positive numeric or parse as a positive
+ * numeric and should be removed when set to a falsey value.
+ * @type {Object}
+ */
+ hasPositiveNumericValue: {},
+
+ /**
+ * Whether the property can be used as a flag as well as with a value. Removed
+ * when strictly equal to false; present without a value when strictly equal
+ * to true; present with a value otherwise.
+ * @type {Object}
+ */
+ hasOverloadedBooleanValue: {},
+
+ /**
+ * All of the isCustomAttribute() functions that have been injected.
+ */
+ _isCustomAttributeFunctions: [],
+
+ /**
+ * Checks whether a property name is a custom attribute.
+ * @method
+ */
+ isCustomAttribute: function(attributeName) {
+ for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
+ var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
+ if (isCustomAttributeFn(attributeName)) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ /**
+ * Returns the default property value for a DOM property (i.e., not an
+ * attribute). Most default values are '' or false, but not all. Worse yet,
+ * some (in particular, `type`) vary depending on the type of element.
+ *
+ * TODO: Is it better to grab all the possible properties when creating an
+ * element to avoid having to create the same element twice?
+ */
+ getDefaultValueForProperty: function(nodeName, prop) {
+ var nodeDefaults = defaultValueCache[nodeName];
+ var testElement;
+ if (!nodeDefaults) {
+ defaultValueCache[nodeName] = nodeDefaults = {};
+ }
+ if (!(prop in nodeDefaults)) {
+ testElement = document.createElement(nodeName);
+ nodeDefaults[prop] = testElement[prop];
+ }
+ return nodeDefaults[prop];
+ },
+
+ injection: DOMPropertyInjection
+ };
+
+ module.exports = DOMProperty;
+
+
+/***/ },
+/* 96 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule quoteAttributeValueForBrowser
+ */
+
+ 'use strict';
+
+ var escapeTextContentForBrowser = __webpack_require__(97);
+
+ /**
+ * Escapes attribute value to prevent scripting attacks.
+ *
+ * @param {*} value Value to escape.
+ * @return {string} An escaped string.
+ */
+ function quoteAttributeValueForBrowser(value) {
+ return '"' + escapeTextContentForBrowser(value) + '"';
+ }
+
+ module.exports = quoteAttributeValueForBrowser;
+
+
+/***/ },
+/* 97 */
+/***/ function(module, exports) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule escapeTextContentForBrowser
+ */
+
+ 'use strict';
+
+ var ESCAPE_LOOKUP = {
+ '&': '&',
+ '>': '>',
+ '<': '<',
+ '"': '"',
+ '\'': '''
+ };
+
+ var ESCAPE_REGEX = /[&><"']/g;
+
+ function escaper(match) {
+ return ESCAPE_LOOKUP[match];
+ }
+
+ /**
+ * Escapes text to prevent scripting attacks.
+ *
+ * @param {*} text Text value to escape.
+ * @return {string} An escaped string.
+ */
+ function escapeTextContentForBrowser(text) {
+ return ('' + text).replace(ESCAPE_REGEX, escaper);
+ }
+
+ module.exports = escapeTextContentForBrowser;
+
+
+/***/ },
+/* 98 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactComponentBrowserEnvironment
+ */
+
+ /*jslint evil: true */
+
+ 'use strict';
+
+ var ReactDOMIDOperations = __webpack_require__(99);
+ var ReactMount = __webpack_require__(118);
+
+ /**
+ * Abstracts away all functionality of the reconciler that requires knowledge of
+ * the browser context. TODO: These callers should be refactored to avoid the
+ * need for this injection.
+ */
+ var ReactComponentBrowserEnvironment = {
+
+ processChildrenUpdates:
+ ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
+
+ replaceNodeWithMarkupByID:
+ ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
+
+ /**
+ * If a particular environment requires that some resources be cleaned up,
+ * specify this in the injected Mixin. In the DOM, we would likely want to
+ * purge any cached node ID lookups.
+ *
+ * @private
+ */
+ unmountIDFromEnvironment: function(rootNodeID) {
+ ReactMount.purgeID(rootNodeID);
+ }
+
+ };
+
+ module.exports = ReactComponentBrowserEnvironment;
+
+
+/***/ },
+/* 99 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactDOMIDOperations
+ * @typechecks static-only
+ */
+
+ /*jslint evil: true */
+
+ 'use strict';
+
+ var CSSPropertyOperations = __webpack_require__(100);
+ var DOMChildrenOperations = __webpack_require__(109);
+ var DOMPropertyOperations = __webpack_require__(94);
+ var ReactMount = __webpack_require__(118);
+ var ReactPerf = __webpack_require__(77);
+
+ var invariant = __webpack_require__(58);
+ var setInnerHTML = __webpack_require__(117);
+
+ /**
+ * Errors for properties that should not be updated with `updatePropertyById()`.
+ *
+ * @type {object}
+ * @private
+ */
+ var INVALID_PROPERTY_ERRORS = {
+ dangerouslySetInnerHTML:
+ '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
+ style: '`style` must be set using `updateStylesByID()`.'
+ };
+
+ /**
+ * Operations used to process updates to DOM nodes. This is made injectable via
+ * `ReactDOMComponent.BackendIDOperations`.
+ */
+ var ReactDOMIDOperations = {
+
+ /**
+ * Updates a DOM node with new property values. This should only be used to
+ * update DOM properties in `DOMProperty`.
+ *
+ * @param {string} id ID of the node to update.
+ * @param {string} name A valid property name, see `DOMProperty`.
+ * @param {*} value New value of the property.
+ * @internal
+ */
+ updatePropertyByID: function(id, name, value) {
+ var node = ReactMount.getNode(id);
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
+ 'updatePropertyByID(...): %s',
+ INVALID_PROPERTY_ERRORS[name]
+ ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
+
+ // If we're updating to null or undefined, we should remove the property
+ // from the DOM node instead of inadvertantly setting to a string. This
+ // brings us in line with the same behavior we have on initial render.
+ if (value != null) {
+ DOMPropertyOperations.setValueForProperty(node, name, value);
+ } else {
+ DOMPropertyOperations.deleteValueForProperty(node, name);
+ }
+ },
+
+ /**
+ * Updates a DOM node to remove a property. This should only be used to remove
+ * DOM properties in `DOMProperty`.
+ *
+ * @param {string} id ID of the node to update.
+ * @param {string} name A property name to remove, see `DOMProperty`.
+ * @internal
+ */
+ deletePropertyByID: function(id, name, value) {
+ var node = ReactMount.getNode(id);
+ ("production" !== process.env.NODE_ENV ? invariant(
+ !INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
+ 'updatePropertyByID(...): %s',
+ INVALID_PROPERTY_ERRORS[name]
+ ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
+ DOMPropertyOperations.deleteValueForProperty(node, name, value);
+ },
+
+ /**
+ * Updates a DOM node with new style values. If a value is specified as '',
+ * the corresponding style property will be unset.
+ *
+ * @param {string} id ID of the node to update.
+ * @param {object} styles Mapping from styles to values.
+ * @internal
+ */
+ updateStylesByID: function(id, styles) {
+ var node = ReactMount.getNode(id);
+ CSSPropertyOperations.setValueForStyles(node, styles);
+ },
+
+ /**
+ * Updates a DOM node's innerHTML.
+ *
+ * @param {string} id ID of the node to update.
+ * @param {string} html An HTML string.
+ * @internal
+ */
+ updateInnerHTMLByID: function(id, html) {
+ var node = ReactMount.getNode(id);
+ setInnerHTML(node, html);
+ },
+
+ /**
+ * Updates a DOM node's text content set by `props.content`.
+ *
+ * @param {string} id ID of the node to update.
+ * @param {string} content Text content.
+ * @internal
+ */
+ updateTextContentByID: function(id, content) {
+ var node = ReactMount.getNode(id);
+ DOMChildrenOperations.updateTextContent(node, content);
+ },
+
+ /**
+ * Replaces a DOM node that exists in the document with markup.
+ *
+ * @param {string} id ID of child to be replaced.
+ * @param {string} markup Dangerous markup to inject in place of child.
+ * @internal
+ * @see {Danger.dangerouslyReplaceNodeWithMarkup}
+ */
+ dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
+ var node = ReactMount.getNode(id);
+ DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
+ },
+
+ /**
+ * Updates a component's children by processing a series of updates.
+ *
+ * @param {array